小编Jon*_*ida的帖子

从Java Array获得前四大值

我试图从整数数组输入中找到前4个最大值.例如,对于给定的输入数组{1232,-1221,0,345,78,99}将返回{1232,345,99,78}作为前4个最大值.我用下面的方法解决了这个问题.但我仍然不满足于它的时间效率.当输入变大时,是否有机会更多地优化方法?任何线索都非常感谢.谢谢.

public int[] findTopFourMax(int[] input) {
int[] topFourList = { Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE,       Integer.MIN_VALUE };
for (int current : input) {
    if (current > topFourList[0]) {
        topFourList[3] = topFourList[2];
        topFourList[2] = topFourList[1];
        topFourList[1] = topFourList[0];
        topFourList[0] = current;
    } else if (current > topFourList[1]) {
        topFourList[3] = topFourList[2];
        topFourList[2] = topFourList[1];
        topFourList[1] = current;
    } else if (current > topFourList[2]) {
        topFourList[3] = topFourList[2];
        topFourList[2] = current;
    } else if (current > topFourList[3]) {
        topFourList[3] = current;
    }
}
return …
Run Code Online (Sandbox Code Playgroud)

java arrays sorting algorithm

5
推荐指数
1
解决办法
1万
查看次数

标签 统计

algorithm ×1

arrays ×1

java ×1

sorting ×1