There are basically two methods
- One is to use java set to do
- The second is to use sort + bisection/double pointer to do
Achieve 2
After sorting, you can compare the maximum and minimum values of the next two arrays to see if there is a solution. You can prune when there is a large amount of data.
int max1,max2,min1,min2;
if(nums1.length==0||nums2.length==0) return new int[0];
max1=nums1[nums1.length-1];//看到长度-1,考虑是否越界
min1=nums1[0];
max2=nums2[nums2.length-1];
min2=nums2[0];
if(max1<min2||min1>max2) return new int[0];
Double pointer
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Arrays.sort(nums2);
Arrays.sort(nums1);
int[] ans=new int[nums2.length];
int cot=0;
int j=0;
int i=0;
while(i!=nums1.length){
if(j==nums2.length) break;
if(nums1[i]==nums2[j]){
j++;
if(cot>=1&&nums1[i]==ans[cot-1]){
i++;
continue;
}
ans[cot++]=nums1[i];
}else if(nums1[i]>nums2[j]) j++;
else if(nums1[i]<nums2[j]) i++;
}
return Arrays.copyOf(ans,cot);
}
}
Two points
The two arrays have been sorted and can be divided into two.
It's nothing more than traversing one array and dicing in another array.
Achieve 1
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> s1=new HashSet<>();
Set<Integer> s2=new HashSet<>();
for(Integer am:nums1) {
s1.add(am);
}
for(Integer am:nums2) s2.add(am);
int size=Math.max(s1.size(),s2.size());
int[] ans=new int[size];
int index=0;
for(Integer am:s1){
if(s2.contains(am)){
ans[index++]=am;
}
}
return Arrays.copyOf(ans,index);
}
}