给定两个整数数组nums1and nums2,返回它们的交集数组。结果中的每个元素必须出现与它在两个数组中显示的一样多的次数,并且您可以按任何顺序返回结果。
示例 1:
输入: nums1 = [1,2,2,1],nums2 = [2,2]
输出: [2,2]
示例 2:
输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出: [4,9]
解释: [9,4] 也被接受。
约束:
1 <= nums1.length, nums2.length <= 1000
0 <= nums1[i], nums2[i] <= 1000
方法1Map
- 建立一个用其中一个数组建立一个map, 遍历另一个数组的数是否存在map中, 存在则存入需要输出的结果数组中并将对应数的value-1
- 为了节省空间, 用较小的数组建立map
- 将key对应的value值-1: map.values().removeIf(f -> f == 0);
- 将结果List输出为int[]: res.stream().mapToInt(i->i).toArray();
class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
int l1 = nums1.length, l2 = nums2.length;
int[] temp = new int[]{};
int[] temp2 = new int[]{};
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
if (l1 < l2) {
temp = nums1;
temp2 = nums2;
} else {
temp = nums2;
temp2 = nums1;
}
for (int i : temp) {
if (map.containsKey(i)) {
map.put(i, map.get(i) + 1);
}else{
map.put(i, 1);
}
}
List<Integer> res =new ArrayList<Integer>();
for (int i=0;i< temp2.length;i++) {
if (!map.containsKey(temp2[i])) {
continue;
} else {
res.add(temp2[i]);
map.put(temp2[i], map.get(temp2[i]) - 1);
map.values().removeIf(f -> f == 0);
}
}
return res.stream().mapToInt(i->i).toArray();
}
}
时间复杂度O(n+m)
但是leetcode运行了15ms看起来比较慢, 所以有了下面的想法
方法2指针
- 将两个数组排序, 然后遍历两个数组, 当都存在时存到结果List中
- 定义两个指针分别指向排序后的数组的第一个数
- 都存在则res.add()
- 不存在则指针向后挪一位
- 当两个指针其中的一个值等于该数组长度时遍历结束
- 返回res.stream().mapToInt(Integer::intValue).toArray();
class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
Arrays.sort(nums1);
Arrays.sort(nums2);
int i=0, j=0;
List<Integer> res = new ArrayList<>();
while(i<nums1.length && j<nums2.length) {
if(nums1[i] == nums2[j]) {
res.add(nums1[i]);
i++;
j++;
} else if (nums1[i] < nums2[j]) {
i++;
} else {
j++;
}
}
return res.stream().mapToInt(Integer::intValue).toArray();
}
}
时间复杂度O(min(n,m))
leetcode运行了5ms