简体   繁体   English

java比较数组元素

[英]java compare array elements

i have a problem with an exam test.我在考试时遇到问题。 I have two arrays: int[] a, int[] b, with random values.我有两个数组:int[] a, int[] b,带有随机值。 E1 return true if there are two elements of b greater then each element of a.如果 b 的两个元素大于 a 的每个元素,则 E1 返回真。 How do I write "there are two elements of b greater than each element of a"?我如何写“b 的两个元素大于 a 的每个元素”? I can write "there is ONE elements of b greater than each element of a" in this way:我可以这样写“b 的一个元素大于 a 的每个元素”:

public static boolean e1(int[] a, int[] b){
    boolean ris = false;
    boolean ogniA = true;
    int i = 0;
    if(a != null && a.length != 0){ 
        while(ogniA && i<a.length){
            boolean es1= false;
            boolean es2 = false;
            int j = 0;

            if(b!= null && b.length != 0){  
                while(!es1 && j < b.length){
                    if(j%2!=0){
                        es1 = a[i] < b[j];
                    } 

                    j++;

                }ris = es1 ;
            }
            i++;
        }
    }
    return ris;

I need something like this.我需要这样的东西。 Thanks for help.感谢帮助。

So I would solve this problem, by dividing it into smaller problems.所以我会解决这个问题,把它分成更小的问题。 1st you need to find the 2 biggest values in the first array.首先,您需要在第一个数组中找到 2 个最大值。 I presume this should be abstract and work for every array我认为这应该是抽象的并且适用于每个数组

Code (using the example from Andronicus):代码(使用 Andronicus 的示例):

"E1 return true if there are two elements of b greater then each element of a" “如果 b 的两个元素大于 a 的每个元素,则 E1 返回真”

Basically you need the second greater value of array B and the greater value of the array A基本上你需要数组 B 的第二个较大值和数组 A 的较大值

int[] a = {3, 5, 7, 9};
int[] b = {2, 4, 3, 10, 11};

int secondGreatestOfB = IntStream.of(b).boxed()
            .sorted(Comparator.reverseOrder())
            .limit(2)
            .sorted(Comparator.naturalOrder())
            .limit(1)
            .findFirst().orElse(0);

System.out.println(areTheTwoBiggestNumbersOfArrayBbiggerThanAllValuesFromArrayA(a, secondGreatestOfB));

private static boolean areTheTwoBiggestNumbersOfArrayBbiggerThanAllValuesFromArrayA(int[] a, int secondGreatestOfArrayB) {
    return secondGreatestOfArrayB > IntStream.of(a).max().orElse(0);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM