1. 程式人生 > >LeetCode349. Intersection of Two Arrays(兩個陣列的交集)JAVA實現

LeetCode349. Intersection of Two Arrays(兩個陣列的交集)JAVA實現

Given two arrays, write a function to compute their intersection.

Example 1:

Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2]

Example 2:

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [9,4]

Note:

  • Each element in the result must be unique.
  • The result can be in any order.

給定兩個陣列,編寫一個函式來計算它們的交集。

示例 1:

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

示例 2:

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

說明:

  • 輸出結果中的每個元素一定是唯一的。
  • 我們可以不考慮輸出結果的順序。

JAVA實現思路:直接暴力迴圈求解的時間複雜度為O(n2),因此考慮縮減時間複雜度為O(nlog2n)。將兩個陣列排好序,再從頭對比是個辦法。

class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        int len = nums1.length>nums2.length?nums2.length:nums1.length;
        int []temp = new int[len];
        int k=0;
        int i=0,j=0;
        while(i<nums1.length && j<nums2.length){
            if(nums1[i]==nums2[j]){     //相等就考慮是並集
                if(k==0 || temp[k-1]!=nums1[i]){  //解決連續相等情況  比如[1,1,2,2]和[2,2]
                    temp[k++]=nums1[i];
                }
                i++;
                j++;
            }
            else if(nums1[i]>nums2[j])
                j++;
            else
                i++;
        }
        int []res = new int[k];
        for(i=0;i<k;i++)
            res[i]=temp[i];
        return res;
    }
}