java - Remove elements from HashSet on iteration -
suppose have hashset
:
[1, 2, 3, 4, 5, 6]
i want iterate on in such way, given sum, 6, while iterating on elements, if find 2 elements in set
having sum = 6, want remove other one. e. g., if iterating on 1, should remove 5. trying this:
hashset<integer> hs = new hashset(arr); int sum = 6; for(int num : hs) { if(hs.contains(sum - num)) { hs.remove(sum - num); } }
obviously throws java.util.concurrentmodificationexception
. approach use iterator removes current element , not take other element parameter. else can use?
update: know techniques use additional set , all. wanted optimal solution without increasing time , space complexity, if that's possible.
keep running set of numbers have found.
this allow have one-pass solution.
start empty running set, , iterate through set of numbers. each element iterate through, if sum-compliment in set, remove iterator. otherwise, add running set.
hashset<integer> hs = new hashset(arr); hashset<integer> running = new hashset(); int sum = 6; iterator<integer> iter = hs.iterator(); while (iter.hasnext()) { int num = iter.next(); if (running.contains(sum - num)) { iter.remove(); } else { running.add(num); } }
this code modify original hashset
, , both hashset
s contain same contents @ end of code block. in case, might better use running
set @ end of code , not modify original. make code far more flexible , reusable.
Comments
Post a Comment