一、先排序,然后用两个指针查找相同的元素
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set1 = new HashSet<>();
Set<Integer> set2 = new HashSet<>();
for (int num : nums1){
set1.add(num);
}
for (int num : nums2){
set2.add(num);
}
set1.retainAll(set2);
int nums[] = new int[set1.size()];
int index = 0;
for (int num : set1){
nums[index++] = num;
}
return nums;
}
}
二、转换成两个set,然后直接求交集
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set1 = new HashSet<>();
Set<Integer> set2 = new HashSet<>();
for (int num : nums1){
set1.add(num);
}
for (int num : nums2){
set2.add(num);
}
set1.retainAll(set2);
int nums[] = new int[set1.size()];
int index = 0;
for (int num : set1){
nums[index++] = num;
}
return nums;
}