Suppose I have a HashSet
:
[1, 2, 3, 4, 5, 6]
I want to iterate over it in such a way, that for a given sum, say 6, while iterating over the elements, if I find 2 elements in the Set
having sum = 6, I want to remove the other one. E. g., if I am iterating over 1, I should remove 5. I was trying to do something like this:
HashSet<Integer> hs = new HashSet(arr);
int sum = 6;
for(int num : hs) {
if(hs.contains(sum - num)) {
hs.remove(sum - num);
}
}
Obviously it throws java.util.ConcurrentModificationException
. Another approach is to use iterator but it removes the current element and does not take any other element as parameter. What else can I use?
Update: I know the techniques to use an additional set and all. I just wanted a very optimal solution without increasing the time and space complexity, if that's possible.