1. Intersection of Two Arrays
https://www.cnblogs.com/grandyang/p/5533305.html
思路一:對(duì)兩數(shù)組進(jìn)行排序,然后比較大小。比如相等,則加到set中;否則,讓小的那一方指針后移。
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Arrays.sort(nums1);
Arrays.sort(nums2);
Set<Integer> result= new HashSet<Integer>();
int i=0;
int j=0;
while(i<nums1.length&&j<nums2.length){
if(nums1[i] == nums2[j]){
result.add(nums1[i]);
i++;
j++;
}
else if(nums1[i]>nums2[j]){
j++;
}
else if(nums1[i]<nums2[j]){
i++;
}
}
int[] res = new int[result.size()];
Object[] ob = result.toArray();
for(int y=0;y<result.size();y++){
res[y]=(int)ob[y];
}
return res;
}
}
思路2:利用map。把數(shù)組1放到map中,然后遍歷數(shù)組2,如果元素在map中,則加入到結(jié)果集里。