350. Intersection of Two Arrays II (Easy)
https://leetcode.com/problems/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?
Solutions
1.
class Solution {
// Use map to keep the count of each element in nums1, then compare with nums2.
public int[] intersect(int[] nums1, int[] nums2) {
if (nums1 == null || nums1.length == 0 || nums2 == null || nums1.length == 0) {
return new int[0];
}
List<Integer> tmp = new ArrayList<>();
Map<Integer, Integer> freq = new HashMap<>();
for (int i = 0; i < nums1.length; i++) {
if (!freq.containsKey(nums1[i])) {
freq.put(nums1[i], 0);
}
freq.put(nums1[i], freq.get(nums1[i]) + 1);
}
for (int i = 0; i < nums2.length; i++) {
if (!freq.containsKey(nums2[i]) || freq.get(nums2[i]) == 0) {
continue;
}
freq.put(nums2[i], freq.get(nums2[i]) - 1);
tmp.add(nums2[i]);
}
int[] ans = new int[tmp.size()];
for (int i = 0; i < tmp.size(); i++) {
ans[i] = tmp.get(i);
}
return ans;
}
}
2.
class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
if (nums1 == null || nums1.length == 0 || nums2 == null || nums1.length == 0) {
return new int[0];
}
Arrays.sort(nums1);
Arrays.sort(nums2);
int i = 0;
int j = 0;
ArrayList<Integer> list = new ArrayList<>();
while (i < nums1.length && j < nums2.length) {
/*
// Do not separate the condition statements since i, j may be changed.
// It will affect the followup code if not move to the next iteration.
if (nums1[i] > nums2[j]) {
j++;
}
if (nums1[i] < nums2[j]) {
i++;
}
if (nums1[i] == nums2[j]) {
list.add(nums1[i]);
i++;
j++;
}
*/
if (nums1[i] > nums2[j]) {
j++;
} else if (nums1[i] < nums2[j]) {
i++;
} else { // nums1[i] == nums2[j]
list.add(nums1[i]);
i++;
j++;
}
}
int[] ans = new int[list.size()];
for (i = 0; i < list.size(); ++i) {
ans[i] = list.get(i);
}
return ans;
}
}