两个数组的交集(简单)
2020年6月19日
题目来源:力扣
解题
- 排序去重对比
看到题目要求,输出结果可以无序,就想到了排序
结果又要求唯一,那么就先去重,这里去重我使用了双指针原地去重
最后就是对比,使用循环对比数值,这里利用了已经排完序的特点,后面的数肯定会越来越大,那后面的数就不用对比前面对比过的数了
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
if(nums1==null ||nums1.length==0 ||nums2==null ||nums2.length==0) return new int[0];
int len1=sortdr(nums1);
int len2=sortdr(nums2);
int[] nums3=len1<len2 ? new int[len1]:new int[len2];
int index=0,jb=0;
for(int i=0;i<len1;i++){
for(int j=jb;j<len2;j++){
if(nums1[i]==nums2[j]){
nums3[index++]=nums1[i];
jb=j;
break;
}
else if(nums1[i]<nums2[j]){
jb=j;
break;
}
}
}
return Arrays.copyOf(nums3,index);
}
public int sortdr(int[] nums){
Arrays.sort(nums);
int la=0;
for(int i=1;i<nums.length;i++){
if(nums[la]!=nums[i]){
nums[++la]=nums[i];
}
}
return la+1;
}
}
- 哈希集合
哈希表做法还是常规思路
class Solution {
public int[] set_intersection(HashSet<Integer> set1, HashSet<Integer> set2) {
int [] output = new int[set1.size()];
int idx = 0;
for (Integer s : set1)
if (set2.contains(s)) output[idx++] = s;
return Arrays.copyOf(output, idx);
}
public int[] intersection(int[] nums1, int[] nums2) {
HashSet<Integer> set1 = new HashSet<Integer>();
for (Integer n : nums1) set1.add(n);
HashSet<Integer> set2 = new HashSet<Integer>();
for (Integer n : nums2) set2.add(n);
if (set1.size() < set2.size()) return set_intersection(set1, set2);
else return set_intersection(set2, set1);
}
}
官方解法竟然调用API,直接用retainAll()取交集,我原地犯傻。这不是犯规吗???
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
HashSet<Integer> set1 = new HashSet<Integer>();
for (Integer n : nums1) set1.add(n);
HashSet<Integer> set2 = new HashSet<Integer>();
for (Integer n : nums2) set2.add(n);
set1.retainAll(set2);
int [] output = new int[set1.size()];
int idx = 0;
for (int s : set1) output[idx++] = s;
return output;
}
}