350. Intersection of Two Arrays II - Easy

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;
    }
}

猜你喜欢

转载自www.cnblogs.com/fatttcat/p/10057930.html