思路一:暴力法
class Solution {
//暴力法,两个for循环遍历数组
public int[] intersection(int[] nums1, int[] nums2) {
//使用Set去重
Set<Integer> res = new HashSet<Integer>();
for(int i = 0; i<nums1.length;i++){
for(int j = 0;j<nums2.length;j++){
if(nums1[i] == nums2[j]){
//如果是交集,加入Set中
res.add(nums1[i]);
}
}
}
//将Set转换成数组
return res.stream().mapToInt(Integer::intValue).toArray();
}
}
思路二:使用两个Set来去重,直接使用Set的retainAll()来操作
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set1 = new HashSet<Integer>();
Set<Integer> set2 = new HashSet<Integer>();
//将nums1的元素加入set1中,并且使用set的属性来去重
for(int num : nums1){
set1.add(num);
}
//给nums2去重
for (int num : nums2) {
set2.add(num);
}
//将set1中包含set2的元素全部保留
set1.retainAll(set2);
return set1.stream().mapToInt(Integer::intValue).toArray();
}
}
思路三:排序+双指针
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Arrays.sort(nums1);
Arrays.sort(nums2);
int length1 = nums1.length, length2 = nums2.length;
int[] intersection = new int[length1 + length2];
int index = 0, index1 = 0, index2 = 0;
while (index1 < length1 && index2 < length2) {
int num1 = nums1[index1], num2 = nums2[index2];
if (num1 == num2) {
// 保证加入元素的唯一性
if (index == 0 || num1 != intersection[index - 1]) {
intersection[index++] = num1;
}
index1++;
index2++;
} else if (num1 < num2) {
index1++;
} else {
index2++;
}
}
return Arrays.copyOfRange(intersection, 0, index);
}
}