从另一个arrayList中减去一个arrayList [英] Subtracting one arrayList from another arrayList
问题描述
我有两个arrayLists,我试图从另一个减去一个arrayList。例如,如果我有一个arrayList [1,2,3]并且我试图减去[0,2,4],则得到的arrayList应该是[1,3]。
I have two arrayLists and I am trying to "subtract" one arrayList from another. For example, if I have one arrayList [1,2,3] and I am trying to subtract [0, 2, 4] the resulting arrayList should be [1,3].
List<Integer> a = new ArrayList<>(Arrays.asList(1, 2, 3));
List<Integer> b = Arrays.asList(0, 2, 4);
subtract(a,b) // should return [1,3]
这是我的代码。
//returns a new IntSet after subtracting a from b
// .minus().toString()
ArrayList<Integer> minusArray = new ArrayList<Integer>();
minusArray.addAll(array1);
for(int i =0; i< minusArray.size(); i++){
for(int j = 0; j < array2.size(); j++){
if(minusArray.get(i).equals(array2.get(j))){
minusArray.remove(i);
if(i == 0){
;
}
else if(j == 0){
;
}
else{
i = 0;
j = 0;
}
}
else{}
}
}
return minusArray;
我的代码在某些情况下有效,例如 arrayList1 = [4,6 ]
和 arrayList2 = [6]
它会给我一个 [4]
。但如果我尝试类似 [1,2,4]
和 [0,4,8]
My code works in some cases, like if arrayList1 = [4,6]
and arrayList2 = [6]
it will will give me a result of [4]
. But if I try something like [1,2,4]
and [0,4,8]
我得到这个例外:
java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at IntSet.minus(IntSet.java:119)
at IntSetDriver.main(IntSetDriver.java:62)
这是代码我我想出来了。我已经完成了测试并且对我来说我认为它应该可行。用户输入这些arrayLists并将它们预先排序,我也不知道Hash或big-O。
Here is the code I have come up with. I have done test runs through it and to me I think it should work. The user inputs these arrayLists and they are presorted, I also do not know Hash or big-O.
ArrayList<Integer> minusArray = new ArrayList<Integer>();
minusArray.addAll(array1);
for(int i =0; i< minusArray.size(); i++){
for(int j = 0; j < array2.size(); j++){
if(minusArray.get(i).equals(array2.get(j))){
minusArray.remove(i);
}
else{}
}
}
return minusArray;
推荐答案
你的问题是你的minusArray.remove(。 ..)调用你可以缩小minusArray的大小。要解决此问题,请从array.size()开始 - 1并向后计数到0
Your problem is that in your minusArray.remove(...) call you may shrink the size of the minusArray. To fix this, start at array.size() - 1 and count backwards to 0
检查 - 即使这样也无法修复它。你需要颠倒循环的顺序
Check that - even that won't fix it. You need to reverse the order of your loops
这篇关于从另一个arrayList中减去一个arrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!