349. Intersection of Two Arrays

Solution1:Hashset

思路:nums1保存到Hashset,nums2 check有无
Time Complexity: O(N) Space Complexity: O(N)

Solution2:Two Pointers

思路:排好序后,Two Pointer顺着增序依次对比
Time Complexity: O(NlogN)
Space Complexity: O(N)
也可以是extraO(1)如果返回是list类型(不用提前知道大小)
另外,可以不用set而是遍历的时候就去重

Solution3:Binary search

思路:nums2排好序后,里面二分查找nums1每个元素
Time Complexity: O(NlogN)
Space Complexity: O(N)

Solution1 Code:

class Solution1 {
    public int[] intersection(int[] nums1, int[] nums2) {
        Set set = new HashSet<>();
        Set intersect = new HashSet<>();
        for (int i = 0; i < nums1.length; i++) {
            set.add(nums1[i]);
        }
        for (int i = 0; i < nums2.length; i++) {
            if (set.contains(nums2[i])) {
                intersect.add(nums2[i]);
            }
        }
        int[] result = new int[intersect.size()];
        int i = 0;
        for (Integer num : intersect) {
            result[i++] = num;
        }
        return result;
    }
}

Solution2 Code:

class Solution2 {
    public int[] intersection(int[] nums1, int[] nums2) {
        Set set = new HashSet<>();
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        int i = 0;
        int j = 0;
        while (i < nums1.length && j < nums2.length) {
            if (nums1[i] < nums2[j]) {
                i++;
            } else if (nums1[i] > nums2[j]) {
                j++;
            } else {
                set.add(nums1[i]);
                i++;
                j++;
            }
        }
        int[] result = new int[set.size()];
        int k = 0;
        for (Integer num : set) {
            result[k++] = num;
        }
        return result;
    }
}

Solution3 Code:

class Solution3 {
    public int[] intersection(int[] nums1, int[] nums2) {
        Set set = new HashSet<>();
        Arrays.sort(nums2);
        for (Integer num : nums1) {
            if (binarySearch(nums2, num)) {
                set.add(num);
            }
        }
        int i = 0;
        int[] result = new int[set.size()];
        for (Integer num : set) {
            result[i++] = num;
        }
        return result;
    }
    
    public boolean binarySearch(int[] nums, int target) {
        int low = 0;
        int high = nums.length - 1;
        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (nums[mid] == target) {
                return true;
            }
            if (nums[mid] > target) {
                high = mid - 1;
            } else {
                low = mid + 1;
            }
        }
        return false;
    }
}

你可能感兴趣的:(349. Intersection of Two Arrays)