[LeetCode] NO. 350 Intersection of Two Arrays II

[题目]Given two arrays, write a function to compute their intersection.

Example:
Given nums1 = [1, 2, 2, 1]nums2 = [2, 2], return [2, 2].

 

[题目解析] 这是对于求两个数组交集的延伸,之前求数组交集重复元素不包含在交集内,用set来求。那么这个问题,就可以用hashmap来解决。如下。

    public int[] intersect(int[] nums1, int[] nums2) {
        HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
        List<Integer> lst = new ArrayList<Integer>();
        for(int num : nums1){
            if(map.containsKey(num)){
                map.put(num, map.get(num)+1);
            }else{
                map.put(num,1);
            }
        }
        for(int num : nums2){
            if(map.containsKey(num)){
                lst.add(num);
                int count = map.get(num);
                count--;
                if(count < 1){
                    map.remove(num);
                }else{
                    map.put(num, count);
                }
            }
        }
        int[] result = new int[lst.size()];
        for(int i = 0; i < lst.size(); i++){
            result[i] = lst.get(i);
        }
        return result;
    }

        进一步思考,我们还可以想到另外一种方法,先对两个数组进行排序,两个有序数组求公共部分,遍历的时候参考归并排序的思想,如下所示。

public int[] intersect(int[] nums1, int[] nums2) {
    Arrays.sort(nums1);
    Arrays.sort(nums2);
    List<Integer> temp = new ArrayList<Integer>();
    for (int i = 0, j = 0; i < nums1.length && j < nums2.length;){
        if (nums1[i] < nums2[j]) i++;
        else if (nums1[i] > nums2[j]) j++;
        else {
            temp.add(nums1[i]);
            i++; j++;
        }
    }
    int[] res = new int[temp.size()];
    for (int i = 0; i < temp.size(); i++)
        res[i] = temp.get(i);
    return res;
}

 

posted @ 2016-08-18 22:19  三刀  阅读(143)  评论(0编辑  收藏  举报