BiruLyu
7/29/2017 - 8:54 PM

350. Intersection of Two Arrays II(#).java

public class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        int pnt1 = 0;
        int pnt2 = 0;
        ArrayList<Integer> myList = new ArrayList<Integer>();

        while ((pnt1 < nums1.length) && (pnt2 < nums2.length)) {
            if (nums1[pnt1] < nums2[pnt2]) {
                pnt1++;
            } else if (nums1[pnt1] > nums2[pnt2]) {
                pnt2++;
            } else {
                myList.add(nums1[pnt1]);
                pnt1++;
                pnt2++;
            }
        }

        int[] res = new int[myList.size()];
        for (int i = 0; i < res.length; i++) {
            res[i] = (Integer) myList.get(i);
        }
        return res;
    }
}
public class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int num : nums1) {
            map.put(num, map.getOrDefault(num, 0) + 1);
        }
        List<Integer> res = new ArrayList<>();
        for (int num : nums2) {
            if (map.containsKey(num)) {
                res.add(num);
                int cnt = map.get(num);
                if (--cnt > 0) {
                    map.put(num, cnt);
                } else {
                    map.remove(num);
                }
            }
        }
        int[] ans = new int[res.size()];
        int i = 0;
        for (int num : res) {
            ans[i++] = num;
        } 
        return ans;
    }
}