所以我有一项任务要做,其中涉及不使用集合或映射。任务是创建两个排序整数列表的交集列表,并且不向该列表添加任何重复项。我已经弄清楚了第一部分,但问题是我不知道如何检查要添加的整数是否不在列表中?
我猜有某种循环?
public ArrayList<Integer> Intersection(ArrayList<Integer> A, ArrayList<Integer> B) {
ArrayList<Integer> result = new ArrayList<Integer>();
int i = 0;
int j = 0;
while (i != A.size() && j != B.size()) {
if (A.get(i) < B.get(j)) {
i ++;
}
else if (A.get(i) > B.get(j)) {
j ++;
}
else {
result.add(A.get(i));
i ++; j++;
}
}
return result;
}
}
因此,通过上面的代码,我得到了交集,但它有重复项,例如来自
列表 A [2, 2, 2, 3] 和
列表 B [2,2,3,4]
当预期结果是[2, 3]时,我得到的结果是[2, 2, 3]
最佳答案
- 始终针对接口(interface)编写代码
只需添加一张支票。检查下面代码中的注释
public static List<Integer> intersection(List<Integer> A, List<Integer> B) { List<Integer> result = new ArrayList<Integer>(); int i = 0; int j = 0; while (i != A.size() && j != B.size()) { if (A.get(i) < B.get(j)) { i++; } else if (A.get(i) > B.get(j)) { j++; } else { // If already contains item dont add again if (!result.contains(A.get(i))) { result.add(A.get(i)); } i++; j++; } } return result; } public static void main(String[] args) { List<Integer> r = intersection(Arrays.asList(2, 2, 2, 3), Arrays.asList(2, 2, 3, 4)); System.out.println(r); }
关于java - 在向列表中添加另一个数字之前,如何检查列表中是否有重复项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57874878/