1.题目描述
给你两个整数数组 nums1 和 nums2 ,请你以数组形式返回两数组的交集。返回结果中每个元素出现的次数,应与元素在两个数组中都出现的次数一致(如果出现次数不一致,则考虑取较小值)。可以不考虑输出结果的顺序。
输入:nums1 = [1,2,2,1], nums2 = [2,2]
输出:[2,2]
输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出:[4,9]
2.解题思路及代码
- 方法一:哈希表
思路:该题与349题非常类似,349题要求输出结果不包含重复的元素。本题可以这样设计:
1,使用数据结构Map<Integer,Integer>来存储较长数组元素及其元素个数,利用一个新数组来保存结果。
2,遍历较短的元素,并判断map中是否包含该元素且对应的元素个数是否大于0,如果满足则对应的value值减一。
3,最后截取新数组的有效长度。
具体代码如下:
public static int[] intersect2(int[] nums1, int[] nums2) {
Map<Integer, Integer> map = new HashMap<>();
int[] result = new int[nums1.length + nums2.length];
int index = 0;
for (int n : nums1) {
map.put(n, map.getOrDefault(n, 0) + 1);
}
for (int s : nums2) {
if (map.containsKey(s) && map.get(s) > 0) {
result[index++] = s;
int count = map.get(s)-1;
map.put(s, count);
}
}
return Arrays.copyOfRange(result, 0, index);
}
时间复杂度:O(n)
空间复杂度:O(l)
- 方法二:排序+双指针
思路:
1,先对两个数组进行排序。
2,设置两个指针分别指向两个数组的头部,遍历两个数组。
3,将相等的值放入新的数组中。
具体代码如下:
public static int[] intersect(int[] nums1, int[] nums2) {
if (nums1.length > nums1.length) {
return intersect(nums2, nums1);
}
Arrays.sort(nums1);
Arrays.sort(nums2);
int n1 = nums1.length;
int n2 = nums2.length;
int[] result = new int[n1 + n2];
int index = 0;
int index1 = 0, index2 = 0;
while (index1 < n1 && index2 < n2) {
if (nums1[index1] == nums2[index2]) {
result[index++] = nums1[index1];
index1++;
index2++;
} else if (nums1[index1] > nums2[index2]) {
index2++;
} else {
index1++;
}
}
return Arrays.copyOfRange(result, 0, index);
}
时间复杂度:O(nlogn)
空间复杂度:O(logn)
题目链接:https://leetcode-cn.com/problems/intersection-of-two-arrays-ii