349. 两个数组的交集

题目:定两个数组,编写一个函数来计算它们的交集
解法一:利用set集合去重复,再遍历其中一个set即可
代码:
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set set1 = new HashSet();
Set set2 = new HashSet();
Set set3 = new HashSet();

    for(int i =0;i<nums1.length;i++){
        set1.add(nums1[i]);
    }   
    for(int i=0;i<nums2.length;i++){
        set2.add(nums2[i]);
    }
    for(int i:set2){
        if(set1.contains(i)){
            set3.add(i);
        }
    }
    int[] ret = new int[set3.size()];
    int j =0;
    for(int i :set3){
        ret[j++] = i;
    }
    return ret;
}

}
注意:对于int[]数组,不能直接使用set.toArray(array)和asList()方法。

解法二:排序+双指针
思路:i和j分别指向两个数组的开头,当发现元素相同,则加入到结果数组中,否则谁小谁向后挪
代码:class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Arrays.sort(nums1);
Arrays.sort(nums2);
int[] ret = new int[nums1.length+nums2.length];
int i=0,j=0,k=0;
while(i<nums1.length&&j<nums2.length){
if(nums1[I] == nums2[j]){
if(k == 0 || nums1[I] != nums1[i-1]){ //去重复
ret[k] = nums1[i];
k++;
}
i++;
j++;
} else if(nums1[I] > nums2[j]){
j++;
} else{
i++;
}
}
return Arrays.copyOfRange(ret,0,k);
}
}

posted @ 2020-11-02 21:58  for_ward  阅读(44)  评论(0)    收藏  举报