LintCode - 两数组的交 II(普通)

版权声明:本文为博主原创文章,未经博主允许不得转载。

难度:容易
要求:

计算两个数组的交

注意事项
每个元素出现次数得和在数组里一样答案可以以任意顺序给出

样例

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

思路

/**
     * @param nums1 an integer array
     * @param nums2 an integer array
     * @return an integer array
     */
    public int[] intersection(int[] nums1, int[] nums2) {
        if(nums1 == null || nums2 == null ){
            return null;
        }
        
        HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
        for(int i = 0; i < nums1.length; i++){
            int value = nums1[i];
            if(map.containsKey(value)){
                map.put(value,map.get(value) + 1);
            }else{
                map.put(value,1);
            }
        }
        
        List<Integer> list = new ArrayList<Integer>();
        
        for(int i = 0; i < nums2.length; i++){
            int value = nums2[i];
            if(map.containsKey(value) && map.get(value) > 0){
                list.add(value);
                map.put(value,map.get(value) - 1);
            }
        }
        
        int[] result = new int[list.size()];
        int index = 0;
        for(Integer i : list){
            result[index++] = i;
        }
        return result;
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,899评论 25 709
  • 版权声明:本文为博主原创文章,未经博主允许不得转载。 难度:容易 要求: 返回两个数组的交 样例 思路:
    柒黍阅读 307评论 0 0
  • 版权声明:本文为博主原创文章,未经博主允许不得转载。 难度:容易 要求: 给定一个排序数组,在原数组中删除重复出现...
    柒黍阅读 410评论 0 0
  • 1. 远足 希拉穆仁大草原,七月骄阳似火,地面上只有三个小黑点在缓慢移动。一位美国来的基因学女博士,一位瑞士来的大...
    方嘉一阅读 536评论 11 6
  • 此刻,我正坐在西塘一个文艺气息的酒吧里。对面舞台上一男一女,干净清新,深情款款地唱着《成都》。 我静静听着,临窗远...
    我是沐馨阅读 479评论 2 5