350. 两个数组的交集II
集合
import java.util.ArrayList;
import java.util.HashMap;
class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
/**
* 用map存储元素和出现的次数
* 用list存储交集元素
* 底层为哈希表的contains()方法的时间复杂度为O(1)
*/
HashMap map = new HashMap<>();
ArrayList list = new ArrayList<>();
for (int n : nums1){
if (!map.containsKey(n)){
map.put(n, 1);
}
else {
map.put(n, map.get(n) + 1);
}
}
for (int n : nums2){
if (map.containsKey(n) && map.get(n) > 0){
list.add(n);
map.put(n, map.get(n) - 1);
}
}
/**
* list.stream().mapToInt(k->k).toArray()方法将ArrayList转换为int[]数组
*/
int[] res = list.stream().mapToInt(k->k).toArray();
return res;
}
}
/**
* 时间复杂度 O(n)
* 空间复杂度 O(n)
*/
双指针
import java.util.ArrayList;
import java.util.Arrays;
class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
/**
* 先对数组进行排序,时间复杂度为O(nlogn)
* 然后使用双指针,从头遍历两个数组,每次让元素小的那个右移,直到二者相等
*/
Arrays.sort(nums1);
Arrays.sort(nums2);
int i = 0;
int j = 0;
ArrayList list = new ArrayList<>();
while (i < nums1.length && j < nums2.length){
if (nums1[i] < nums2[j]){
i++;
}
else if (nums1[i] > nums2[j]){
j++;
}
else {
list.add(nums1[i]);
i++;
j++;
}
}
return list.stream().mapToInt(k->k).toArray();
}
}
/**
* 时间复杂度 O(nlogn)
* 空间复杂度 O(n)
*/
https://leetcode-cn.com/problems/intersection-of-two-arrays-ii/