LeetCode每日一题:两个数组的交集II(No.350)

369 阅读1分钟

题目:两个数组的交集 II


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

示例:


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

输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出: [4,9]

思考:


这道题先将两个数组排序。
然后用两个指针i、j对两个数组开始遍历,相同的元素保存到结果集中,不同的元素将较小元素指针向后移。

实现:


class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        int length1 = nums1.length;
        int length2 = nums2.length;
        ArrayList<Integer> list=new ArrayList<Integer>();
        for(int i=0,j=0;i<length1 && j<length2;) {
            if(nums1[i] == nums2[j]) {
                list.add(nums1[i]);
                i++;
                j++;
            }
            else if(nums1[i] > nums2[j]) {
                j++;
            }
            else {
                i++;
            }
        }
        int[] result = new int[list.size()];
        for (int count=0;count<list.size();count++){
            result[count]=list.get(count);
        }
        return result;
    }
}