LeetCode 350. Intersection of Two Arrays II [Easy]

题目来源:https://leetcode.com/problems/intersection-of-two-arrays-ii

题目难度:Easy

题目

Given two arrays, write a function to compute their intersection.

Example 1:

1
2
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]

Example 2:

1
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?

解答1[Java]

思路

借助一个 Map,先统计数组1中每一个数组的个数,然后再遍历数组2,如果 Map 中存在此元素,则加入到结果数组,并且把 Map 中统计的数量减去 1。

实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
HashMap<Integer, Integer> map = new HashMap<>();
ArrayList<Integer> result = new ArrayList<>();
for (int value : nums1) {
if (map.containsKey(value)) {
map.put(value, map.get(value) + 1);
} else {
map.put(value, 1);
}
}

for (int value : nums2) {
if (map.containsKey(value) && map.get(value) > 0) {
result.add(value);
map.put(value, map.get(value) - 1);
}
}

int[] resultArray = new int[result.size()];
for (int i = 0; i < result.size(); i++) {
resultArray[i] = result.get(i);
}

return resultArray;
}
}

复杂度分析

HashMap 的 get() 时间复杂度为 $O(1)$。

解答2[Java]

思路

先对两个数组进行排序,然后两个数组分别设一个指针,判断当前指针指向的元素是否相等,如果相等就把指针当前指向的元素加入结果数组。如果不相等,哪个指向的元素更小,哪个指针向右移动,另外一个指针保持位置不变。

实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
List<Integer> intersection = new ArrayList<>();
Arrays.sort(nums1);
Arrays.sort(nums2);

int i = 0;
int j = 0;
while (i < nums1.length && j < nums2.length) {
if (nums1[i] == nums2[j]) {
intersection.add(nums2[j]);
i++;
j++;
} else if (nums1[i] > nums2[j]) {
j++;
} else {
// nums[i] < nums[j]
i++;
}
}


int[] res = new int[intersection.size()];
for (int k = 0; k < intersection.size(); k++) {
res[k] = intersection.get(k);
}

return res;
}
}