zoukankan      html  css  js  c++  java
  • 350. Intersection of Two Arrays II

    Given two arrays, write a function to compute their intersection.

    Example 1:

    Input: nums1 = [1,2,2,1], nums2 = [2,2]
    Output: [2,2]
    

    Example 2:

    Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
    Output: [4,9]

    Note:

    • Each element in the result should appear as many times as it shows in both arrays.
    • The result can be in any order.

    Follow up:

    • What if the given array is already sorted? How would you optimize your algorithm?
    • What if nums1's size is small compared to nums2'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?

    M1: hash table

    先遍历nums1,用hashmap存其中的元素及频率。再遍历nums2,如果map中存在当前元素并且频率 > 1,加入到res中,并更新map中的频率(-1)。最后把res从arraylist转成int[]即可

    时间:O(N),空间:O(N)

    class Solution {
        public int[] intersect(int[] nums1, int[] nums2) {
            HashMap<Integer, Integer> map = new HashMap<>();
            List<Integer> tmp = new ArrayList<>();
            
            for(int n : nums1) {
                map.put(n, map.getOrDefault(n, 0) + 1);
            }
            for(int n : nums2) {
                if(map.containsKey(n) && map.get(n) > 0) {
                    tmp.add(n);
                    map.put(n, map.get(n) - 1);
                }
            }
            
            int[] res = new int[tmp.size()];
            for(int i = 0; i < tmp.size(); i++) {
                res[i] = tmp.get(i);
            }
            return res;
        }
    }

    M2: two pointers

    需要先对两个数组排序,然后two pointer,谁小移谁

    time: O(nlogn), space: O(1)

    class Solution {
        public int[] intersect(int[] nums1, int[] nums2) {
            Arrays.sort(nums1);
            Arrays.sort(nums2);
            List<Integer> list = new ArrayList<>();
            
            int i = 0, j = 0;
            while(i < nums1.length && j < nums2.length) {
                if(nums1[i] == nums2[j]) {
                    list.add(nums1[i]);
                    i++;
                    j++;
                } else if(nums1[i] < nums2[j]) {
                    i++;
                } else {
                    j++;
                }
            }
            
            int[] res = new int[list.size()];
            for(int k = 0; k < list.size(); k++) {
                res[k] = list.get(k);
            }
            return res;
        }
    }
  • 相关阅读:
    表单中input name属性有无[]的区别
    验证器
    模板输出替换
    模型中的数据操作
    2020 倒计时 1 天,Python 工程师找工作更难了?
    80后、90后扎心图鉴
    2019,我赚钱了
    AI在自动化测试领域的应用
    我被裁掉的那一天
    【阿里巴巴】飞猪技术质量招聘
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10057930.html
Copyright © 2011-2022 走看看