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;
        }
    }
    
  • 相关阅读:
    python学习之控制流1
    python学习之字符串转换
    python学习之数据类型与运算符号
    python之获取微信好友列表并保存文档中
    python之微信自动发送消息
    python之微信好友统计信息
    java并发编程--AtomicInteger
    java.time学习
    chrome插件
    classpath和classpath*
  • 原文地址:https://www.cnblogs.com/mapoos/p/13211469.html
Copyright © 2011-2022 走看看