简体   繁体   English

在数组中查找 3 个最大整数

[英]Find 3 max integers in an array

I tried to find largest three elements in an array.我试图在数组中找到最大的三个元素。 So far I've come up with this but it doesn't work properly (The output is 9 8 3):到目前为止,我已经想出了这个,但它不能正常工作(output 是 9 8 3):

public class Test {

    public static void main(String[] args) {
        int max1, max2, max3;
        int[] test= {2,4,8,3,9,1};
        
        max1= test[0];
        max2= test[0];
        max3= test[0];
        for(int i = 1; i < test.length; i++) {
            if(max1 < test[i]) {
                max2= max1;
                max1= test[i];
            }
            else if (max2 < test[i]) {
                max3= max2;
                max2= test[i];
            }
            else if (max3 < test[i]) {
                max3= test[i];
            }

        }
        System.out.println(max1 + " " + max2 + " " + max3);
        
    }

}

I've managed to do the largest 2 integers but I can't do 3. How can I write the code using only 1 iteration through the array?我已经设法做最大的 2 个整数,但我不能做 3 个。如何仅使用 1 次遍历数组来编写代码?

In the first 'if' statement you do not include:在第一个“if”语句中,您不包括:

max3 = max2

I would use stream s for that job:我会使用stream来完成这项工作:

int[] test= {2,4,8,3,9,1};

String maxValues = Arrays.stream(test).boxed()
        .sorted(Comparator.reverseOrder())
        .limit(3)
        .map(String::valueOf)
        .collect(Collectors.joining(" "));

System.out.println(maxValues);

Output Output

9 8 4
    Arrays.sort(test);
    max1 = test[test.length - 1];
    max2 = test[test.length - 2];
    max3 = test[test.length - 3];
    System.out.println(max1 + " " + max2 + " " + max3);

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

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