簡體   English   中英

在數組中查找 3 個最大整數

[英]Find 3 max integers in an array

我試圖在數組中找到最大的三個元素。 到目前為止,我已經想出了這個,但它不能正常工作(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);
        
    }

}

我已經設法做最大的 2 個整數,但我不能做 3 個。如何僅使用 1 次遍歷數組來編寫代碼?

在第一個“if”語句中,您不包括:

max3 = max2

我會使用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

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