349. 两个数组的交集
哈希表
import java.util.HashSet;
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
/**
* 用集合set1存储nums1的元素,然后将nums2的元素挨个进行对比
* 如果都存在就存在set2中
* 最后将集合的元素添加进一个数组返回
* 底层为哈希表的contains()方法的时间复杂度为O(1)
*/
HashSet<Integer> set1 = new HashSet<>();
HashSet<Integer> set2 = new HashSet<>();
for (int i = 0; i < nums1.length; i++) {
set1.add(nums1[i]);
}
for (int i = 0; i < nums2.length; i++) {
if (set1.contains(nums2[i])){
set2.add(nums2[i]);
}
}
int[] res = new int[set2.size()];
int j = 0;
for (int i : set2){
res[j++] = i;
}
return res;
}
}
/**
* 时间复杂度 O(n)
* 空间复杂度 O(n)
*/
双指针
import java.util.Arrays;
import java.util.HashSet;
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
/**
* 先对数组进行排序,时间复杂度为O(nlogn)
* 然后使用双指针,从头遍历两个数组,每次让元素小的那个右移,直到二者相等
* 使用Set存储元素,保证元素不重复
*/
Arrays.sort(nums1);
Arrays.sort(nums2);
int i = 0;
int j = 0;
HashSet<Integer> set = new HashSet<>();
while (i < nums1.length && j < nums2.length){
if (nums1[i] < nums2[j]){
i++;
}
else if (nums1[i] > nums2[j]){
j++;
}
else {
set.add(nums1[i]);
i++;
j++;
}
}
return set.stream().mapToInt(k->k).toArray();
}
}
/**
* 时间复杂度 O(nlogn)
* 空间复杂度 O(n)
*/
https://leetcode-cn.com/problems/intersection-of-two-arrays/