gpt4 book ai didi

java - 遍历 ArrayList 以获得 5 个最大的数字

转载 作者:行者123 更新时间:2023-11-30 08:29:24 25 4
gpt4 key购买 nike

是的,这是家庭作业,但我需要一些帮助。我已经能够对最高数字进行排序,但之后没有一个数字是正确的。号码列表:http://pastebin.com/Ss1WFGv1现在我们正在学习数组,那么这是简单地用炮弹打苍蝇吗?

    package hw2;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;

public class HW2 {

public static ArrayList<Integer> nums1 = new ArrayList<Integer>();
public static int size = 0;

public static void main(String[] args) throws Exception {
ArrayList<Integer> sortedNums = new ArrayList<Integer>();


readFile();
System.out.println("Name: Jay Bhagat" + "\n" + "Email: xxxxxx");
size = nums1.size();

for(int l = 0; l<=10;l++){
nums1.set(sortThis(nums1, l), 90009);
System.out.println("\n\n");
}


// for (int k = 0; k <= size - 1; k++) {
// System.out.println("Number " + (k + 1) + sortedNums.get(k));
//
// }


}

public static void readFile() throws Exception {
BufferedReader reader = new BufferedReader(new FileReader("L:\\numbers.txt"));

while (reader.readLine() != null) {
nums1.add(Integer.parseInt((reader.readLine())));
}

reader.close();


}

public static int sortThis(ArrayList<Integer> current, int offset) {
int j = 0;
int tempNum = 0;
int curNum = 0;
int finalIndex = 0;
int prevIndex = 0;
int curIndex = 0;

for (j = 0; j < size-offset; j++) {
curIndex = j;
nums1.trimToSize();
curNum = current.get(j);
//Thread.sleep(1000);
if(curNum!=90009){
if (curNum > tempNum) {
tempNum = curNum;
System.out.println(tempNum);
prevIndex = j;
finalIndex = prevIndex;
}
if (curNum < tempNum) {
finalIndex = prevIndex;
}
}



}
return finalIndex;
}
}

最佳答案

一种让您只需遍历列表且不需要排序的方法:

声明一个包含 5 个整数的数组:int[] largest = new int[5];

ArrayList中的前5个元素放入largest中。

从第6个元素开始,查看ArrayList中的每个元素N,如果N大于largest中的任意个元素,抛出largest中当前最小的数,用N代替。

如果您需要排除重复项,可以轻松修改算法(只需跳过任何已经在 largest 中的 ArrayList 元素)。

关于java - 遍历 ArrayList 以获得 5 个最大的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19458733/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com