[LeetCode] #349 两个数组的交集

给定两个数组,编写一个函数来计算它们的交集。

输入:nums1 = [1,2,2,1], nums2 = [2,2]

输出:[2]

使用HashSet去重·

class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        if (nums1 == null || nums2 == null) return null;
        Set<Integer> set1 = new HashSet<>();
        Set<Integer> set2 = new HashSet<>();
        for(int num: nums1) set1.add(num);
        for (int item : nums2) 
            if (set1.contains(item)) set2.add(item);
        int[] res = new int[set2.size()];
        int index = 0;
        for (int num : set2) {
            res[index] = num;
            index++;
        }
        return res;
    }
}

排序后找相同元素

class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        int length1 = nums1.length, length2 = nums2.length;
        int[] intersection = new int[length1 + length2];
        int index = 0, index1 = 0, index2 = 0;
        while (index1 < length1 && index2 < length2) {
            int num1 = nums1[index1], num2 = nums2[index2];
            if (num1 == num2) {
                if (index == 0 || num1 != intersection[index - 1]) {
                    intersection[index++] = num1;
                }
                index1++;
                index2++;
            } else if (num1 < num2) {
                index1++;
            } else {
                index2++;
            }
        }
        return Arrays.copyOfRange(intersection, 0, index);
    }
}

知识点:

Arrays.copyOfRange(T[ ] original,int from,int to)

将一个原始的数组original,从下标from开始复制,复制到上标to,生成一个新的数组。

注意这里包括下标from,不包括上标to。

总结:

posted @ 2021-09-18 13:40  1243741754  阅读(18)  评论(0编辑  收藏  举报