349 Intersection of Two Arrays

1. Question

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

Example: Given nums1=[1, 2, 2, 1],nums2 =[2, 2], return[2].

Note:

  • Each element in the result must be unique.

  • The result can be in any order.

2. Implementation

(1) Two Pointers

class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        Set<Integer> set = new HashSet<>();

        Arrays.sort(nums1);
        Arrays.sort(nums2);

        int i = 0, 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[] res = new int[set.size()];
        int index = 0;

        for (int e : set) {
            res[index++] = e;
        }
        return res;
    }
}

(2) Binary Search

class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        if (nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0) {
            return new int[0];
        }

        Set<Integer> set = new HashSet<>();

        Arrays.sort(nums2);

        for (int i = 0; i < nums1.length; i++) {
            int index = binarySearch(nums2, nums1[i]);

            if (index != -1) {
                set.add(nums1[i]);
            }
        }

        int[] res = new int[set.size()];
        int index = 0;

        for (int e : set) {
            res[index++] = e;
        }
        return res;
    }

    public int binarySearch(int[] nums, int target) {
        int start = 0, end = nums.length - 1, mid = 0;

        while (start <= end) {
            mid = start + (end - start) / 2;

            if (nums[mid] == target) {
                return mid;
            }
            else if (nums[mid] < target) {
                start = mid + 1;
            }
            else {
                end = mid - 1;
            }
        }
        return -1;
    }
}

3. Time & Space Complexity

Two Pointers: 时间复杂度O(nlogn + mlogm),n为nums1的长度,m为nums2的长度,空间复杂度O(Math.min(m,n))

Binary Search: 时间复杂度O(nlogn + mlogn), 空间复杂度O(Math.min(m, n))

Last updated