1. 程式人生 > >[leetcode350]Intersection of Two Arrays II求數組交集

[leetcode350]Intersection of Two Arrays II求數組交集

length add span lis () 排序 ger code while

List<Integer> res = new ArrayList<>();
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        int i1 = 0;
        int i2 = 0;
        while (i1<nums1.length&&i2<nums2.length)
        {
            if (nums1[i1]<nums2[i2])
                i1++;
            else if
(nums1[i1]>nums2[i2]) i2++; else { res.add(nums1[i1]); i1++; i2++; } } int[] num = new int[res.size()]; for (int i = 0; i < num.length; i++) { num[i] = res.get(i); }
return num;

受上一題的影響,本來想用hashset解決,但是發現不行,就換了排序然後遍歷的方法,如果不相等,小的數的下邊++,相等就添加

[leetcode350]Intersection of Two Arrays II求數組交集