350. 两个数组的交集II
哈希表
import java.util.ArrayList;
import java.util.HashMap;
class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
/**
* 用map存储nums1中的元素和出现的次数,如果nums2中相同元素个数超过了nums1,则不会被添加
* 底层为哈希表的contains()方法的时间复杂度为O(1)
*/
HashMap<Integer, Integer> map = new HashMap<>();
ArrayList<Integer> list = new ArrayList<>();
for (int n : nums1){
map.put(n, map.getOrDefault(n, 0) + 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<Integer> 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/