zoukankan      html  css  js  c++  java
  • 0350. Intersection of Two Arrays II (E)

    Intersection of Two Arrays II (E)

    题目

    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?

    题意

    取两数组的交集,包含所有重复元素

    思路

    普通做法直接用HashMap处理即可。

    排序情况下用类似于归并排序的方法处理。


    代码实现

    Java

    Hash

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

    排序

    class Solution {
        public int[] intersect(int[] nums1, int[] nums2) {
            List<Integer> list = new ArrayList<>();
            Arrays.sort(nums1);
            Arrays.sort(nums2);
            int p1 = 0, p2 = 0;
            while (p1 < nums1.length && p2 < nums2.length) {
                if (nums1[p1] > nums2[p2]) {
                    p2++;
                } else if (nums1[p1] < nums2[p2]) {
                    p1++;
                } else {
                    list.add(nums1[p1]);
                    p1++;
                    p2++;
                }
            }
    
            int[] res = new int[list.size()];
            int i = 0;
            for (int num : list) {
                res[i++] = num;
            }
    
            return res;
        }
    }
    
  • 相关阅读:
    HTML基础-3
    HTML基础-2
    HTML基础-1
    hdu 1709 The Balance(母函数)
    hdu 2082 找单词(母函数)
    hdu 1085 Holding Bin-Laden Captive!(母函数)
    hdu 1028 Ignatius and the Princess III(母函数)
    hdu 1027 Ignatius and the Princess II(正、逆康托)
    康托展开、康托逆展开原理
    hdu 4288 Coder(单点操作,查询)
  • 原文地址:https://www.cnblogs.com/mapoos/p/13211469.html
Copyright © 2011-2022 走看看