【一次过】Lintcode 548.两数组的交 II

 

计算两个数组的交

样例

nums1 = [1, 2, 2, 1], nums2 = [2, 2], 返回 [2, 2].

挑战

  • What if the given array is already sorted? How would you optimize your algorithm?
  • What if nums1's size is small compared to num2's size? Which algorithm is better?
  • What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?

解题思路:

    我们换一种数据结构,用HashMap<int,int>存储,遍历数组1中所有元素的时,key为数组元素,value为该数组元素出现的次数。遍历数组2中元素时,如果HashMap中元素的value值大于0,则value--,并将该元素放入结果数组中,否则continue。最后返回结果数组。

public class Solution {
    /**
     * @param nums1: an integer array
     * @param nums2: an integer array
     * @return: an integer array
     */
    public int[] intersection(int[] nums1, int[] nums2) {
        // write your code here
        Map<Integer, Integer> map = new HashMap<>();
        for(int i : nums1){
            if(map.get(i) == null)
                map.put(i, 1);
            else
                map.put(i, map.get(i)+1);
        }
        
        List<Integer> list = new ArrayList<>();
        
        for(int i : nums2){
            if(map.get(i) != null && map.get(i) > 0){
                list.add(i);
                map.put(i, map.get(i)-1);
            }
        }
        
        int[] res = new int[list.size()];
        for(int i=0; i<res.length; i++)
            res[i] = list.get(i);
        
        return res;
    }
}

挑战:

如果数组全为有序数组,则可以采用双指针法,设置p1与p2分别遍历指向nums1和nums2,当*p1==*p2则保存进结果数组,否则让小的指针++,直到有一方数组遍历完毕结束,代码就不放了。

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值