gpt4 book ai didi

java - ArrayList重复

转载 作者:行者123 更新时间:2023-12-02 08:53:26 25 4
gpt4 key购买 nike

Consider a text file of IDs, with one ID per line, which has duplicate IDs. We would like to eliminate the duplicate IDs by using an ArrayList. Read each ID from the file, add it to the ArrayList if it is not already added, and then output all IDs in the ArrayList to a new text file..

我解决了这个问题,我将添加所有 id,然后检查它们是否存在并删除它们,但是我的医生不希望它们首先添加

 ArrayList<Integer> myid = new ArrayList<Integer>();

int idset,count=14;

while(sc.hasNextInt()) {
idset = sc.nextInt();
myid.add(idset);
}
for (int i = 1; i < myid.size(); i++) {
int a1 = (int) myid.get(i);
int a2 = (int) myid.get(i-1);
if (a1 != a2) {
count--;
}
else {
myid.remove(a1);
}
}
pw.println(myid);
pw.println("duplicate = "+count);

最佳答案

所以,要求并没有要求你计算任何东西......不知道在哪里 count=14来自。

did not want them to be add in the first place

那就不要添加它们

使用 List#contains

while (sc.hasNextInt()) {
idset = sc.nextInt();
if (!myid.contains(idset)) { // <--- here
myid.add(idset);
}
}
myid.foreach(pw::println);

注意:上面的代码有O(n^2)运行时复杂性,以及Set<Integer>更适合这个问题,其运行时间为 O(n) ,对于 n 的集合id。

你可以做 new ArrayList<>(set)返回一个列表(如果您确实想要一个列表)

关于java - ArrayList重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60631392/

25 4 0