2 sum?
Determine if there exist two elements in a given array, the sum of which is the given target number.
Solution: HashSet
public boolean existSum(int[] array, int target){
Set<Integer> set = new HashSet<>();
for (int num : array){
if (set.contains(target - num){
return true;
}
set.add(num);
}
return false;
}
Time comp: O(N) check every element, O(1) average add/search time
Space comp: O(N) every element add to
Last updated
Was this helpful?