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?

代码

public class Solution {
    /**
     * @param nums1 an integer array
     * @param nums2 an integer array
     * @return an integer array
     */
    public int[] intersection(int[] nums1, int[] nums2) {
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        // 计算nums1[i]出现的次数
        for (int i = 0; i < nums1.length; ++i) {
            if (map.containsKey(nums1[i])) {
                map.put(nums1[i], map.get(nums1[i]) + 1); 
            }
            else {
                map.put(nums1[i], 1);
            }
        }

        List<Integer> results = new ArrayList<Integer>();

        // 将nums2中与nums1中相同的数存到results中
        // 每存nums2[i]到result里,hash表里的次数减一
        // 注意对hash表次数为0的越界判断
        for (int i = 0; i < nums2.length; ++i) {
            if (map.containsKey(nums2[i]) &&
                map.get(nums2[i]) > 0) {
                results.add(nums2[i]);
                map.put(nums2[i], map.get(nums2[i]) - 1); 
            }
        }

        int result[] = new int[results.size()];
        for(int i = 0; i < results.size(); ++i) {
            result[i] = results.get(i);
        }

        return result;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 有你 连空气都是甜的 幸福如潺潺溪水 围绕着我 明明是我先到的极限 明明是我带你去的 明明那是我师兄师姐 结果就因...
    暖心阿欣阅读 209评论 0 1
  • 你在读微信公众号的文章时,会发现题目下面一行的日期前有的是有(原创)标志,有时则没有。微信原创声明功能现在仍处于内...
    用心生活用字记录阅读 480评论 8 7