【发布时间】:2022-11-27 23:40:48
【问题描述】:
我得到了一个 List<Integer>,我试图在一个新数组中返回列表中的 2 个最小整数。
为此,我创建了一个帮助器,用于查找数组中的最小数字,然后在我的主函数中使用它,我希望在其中使用一个运行到 2 的 while 循环,因为我需要 2 个最小的数字,并删除第一个(最小)数字,以便找到下一个最小的数字,然后将它们添加到我制作的新数组中。
这是我的代码:
public static int countSorthelper(List<Integer> arr) {
int temp = 0;
int n = 0;
while(n <= 2){
for (int x = 0; x < arr.size(); x++){
for (int y = x+1; y < arr.size() && y <= x+y; y++){
if(arr.get(y) > arr.get(x)){
temp = arr.get(x);
n++;
}
}
}
}
return temp;
}
public static List<Integer> countSort(List<Integer> arr){
int n = 0;
List<Integer> j = new ArrayList<>();
while (n <= 2){
countSorthelper(arr);
arr.remove(countSorthelper(arr));
j.add(countSorthelper(arr));
n++;
}
return j;
}
当我尝试运行它时,输出由于运行时间过多而终止,我需要对我的代码进行哪些更改??
【问题讨论】:
-
查看stackoverflow.com/questions/20518078/how-to-sort-listinteger,对您的输入进行排序并获得两个最小值