HashSet<Integer> set = new HashSet<Integer>();
ArrayList<Integer> res = new ArrayList<Integer>();
//Add all elements to set from array 1
for(int i =0; i< nums1.length; i++) set.add(nums1[i]);
for(int j = 0; j < nums2.length; j++) {
// If present in array 2 then add to res and remove from set
if(set.contains(nums2[j])) {
res.add(nums2[j]);
set.remove(nums2[j]);
}
}
// Convert ArrayList to array
int[] arr = new int[res.size()];
for (int i= 0; i < res.size(); i++) arr[i] = res.get(i);
return arr;
5ms Java Using 1 hashset and time complexity of O(m+n)


Yes, set works similar to how map works, so it will hash the value and search in that particular index.
http://stackoverflow.com/questions/25247854/hashsetcontainsperformance


Same idea, but shorter code,
class Solution { public int[] intersection(int[] nums1, int[] nums2) { Set<Integer> numbers = new HashSet<>(); for (int n : nums1) { numbers.add(n); } int[] res = new int[numbers.size()]; int cursor = 0; for (int n : nums2) { if (numbers.remove(n)) { res[cursor++] = n; } } return Arrays.copyOfRange(res,0,cursor); } }