我试图从整数数组输入中找到前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) 我有一个简单的问题。我正在PriorityQueue我的项目中执行。我的问题是我可以PriorityQueue为Java 设置固定大小吗?
java是否包括一个本机类,该类允许最多数量的元素,并且如果我再输入一个元素,它将自动删除旧的元素(例如,基于自然排序)?
如果没有,我当然可以自己写,但是我只是想问一下。
我有一个int数组,int[] myArray = new int[100];并希望获得最小10(任意n)元素的索引.我怎样才能做到这一点?