350. Intersection of Two Arrays II - Easy
阿新 • • 發佈:2018-12-03
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; } }