【发布时间】:2021-04-07 06:06:02
【问题描述】:
我正在尝试找出哪些数字在列表中出现过一次。例如,[1, 3, 2, 3] 的列表应该返回 [1, 2]。但是,我的代码只返回 [1],当我也尝试打印重复项时,它打印了 [3, 2]。
我不确定我哪里出错了,因为我正在跟踪重复项以确保我不会重复计算一个元素。
还有更有效的方法吗?例如,使用 HashMap?我知道我可以使用 Collections 类,但为了练习,我宁愿避免使用它!
任何帮助和建议将不胜感激。
这是我下面的内容:
import java.util.*;
class Main {
public static void main(String[] args) {
// From a list find which numbers appear once
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(3);
list.add(2);
list.add(3);
ArrayList<Integer> once = new ArrayList<Integer>();
boolean isDuplicate = false;
ArrayList<Integer> duplicate = new ArrayList<Integer>();
for (int i=0; i<list.size(); i++) {
if (!duplicate.contains(list.get(i))){ // if its not a duplicate, continue iterating through the list
for (int j=i+1; j<list.size(); j++) {
if (list.get(i).equals(list.get(j))) { // if its a duplicate
isDuplicate = true;
}
}
if (!isDuplicate) { // if its not a duplicate add to the "once" list
once.add(list.get(i));
} else { // if isDuplicate is true add to the duplicate list
duplicate.add(list.get(i));
}
}
}
System.out.println("Numbers that appear once: " + once + "\nDuplicates: " + duplicate);
}
【问题讨论】:
-
为什么不直接使用Map 来统计列表中每个数字出现的频率?
-
您好,欢迎来到 StackOverflow!也许创建一个 HashSet 将您的列表作为构造函数参数传递给它?像这样:
new HashSet<Integer>(list);这使用 Sets 的唯一性属性为您完成工作。 -
这篇文章是一个可能的解决方案How can I count occurrences with groupBy?
标签: java list arraylist duplicates