首页 > 其他 > 详细

[LeetCode] NO. 350 Intersection of Two Arrays II

时间:2016-08-18 23:18:20      阅读:275      评论:0      收藏:0      [点我收藏+]

[题目]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;
}

 

[LeetCode] NO. 350 Intersection of Two Arrays II

原文:http://www.cnblogs.com/zzchit/p/5785473.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!