/**
* This problem allows duplicate, then we cannot use hashset.
* Solution is using hashmap, the key would be the number in the array,
* and the value is the number of times a key appeared.
* O(n)
*/
public class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
HashMap<Integer, Integer> hm1 = new HashMap<Integer, Integer>();
List<Integer> list = new ArrayList<>();
// iterate the first array save the number and the times it appeared
for (int num1 : nums1) {
if (hm1.containsKey(num1))
hm1.put(num1, hm1.get(num1)+1); // increase count by 1
else
hm1.put(num1, 1);
}
// iterate the second array to find intersection, add number to the list if count is grater than 0
for (int num2 : nums2) {
if (hm1.containsKey(num2) && hm1.get(num2)>0) {
list.add(num2);
hm1.put(num2, hm1.get(num2)-1); // decrease count by 1
}
}
int[] ret = new int[list.size()];
int k = 0;
for (int l : list)
ret[k++] = l;
return ret;
}
}
public class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
List<Integer> list = new ArrayList<>();
// sort tow arrays, O(nlogn)
Arrays.sort(nums1);
Arrays.sort(nums2);
// use two pointer to find intersection
int i = 0, j = 0;
while (i<nums1.length && j<nums2.length) {
if (nums1[i] < nums2[j]) ++i;
else if (nums1[i] > nums2[j]) ++j;
else {
list.add(nums1[i]);
++i; ++j;
}
}
int[] ret = new int[list.size()];
int k = 0;
for (int l : list)
ret[k++] = l;
return ret;
}
}
/** * This problem allows duplicate, then we cannot use hashset. * Solution is using hashmap, the key would be the number in the array, * and the value is the number of times a key appeared. * O