349. Intersection of Two Arrays - Easy

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.

 

M1: binary search

先把nums2排序,然后对于nums1中的每一个元素,在nums2中进行binary search,需要一个set存结果

time: O(nlogn), space: O(1)

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

 

 

M2: hash table

用两个set,先把nums1元素放进set1,如果nums2中也有该元素,放进res set里

time: O(n), space: O(n)

class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        Set<Integer> set1 = new HashSet<>();
        Set<Integer> set2 = new HashSet<>();
        for(int n : nums1) {
            set1.add(n);
        }
        for(int n : nums2) {
            if(set1.contains(n)) {
                set2.add(n);
            }
        }
        
        int[] res = new int[set2.size()];
        int i = 0;
        for(int n : set2) {
            res[i++] = n;
        }
        return res;
    }
}

 

M3: two pointers

需要先对两个数组都排序,并用set存结果去重

time: O(nlogn), space: O(1)

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]) {
                set.add(nums1[i]);
                i++;
                j++;
            } else if(nums1[i] > nums2[j]) {
                j++;
            } else {
                i++;
            }
        }
        
        int[] res = new int[set.size()];
        int k = 0;
        for(int n : set) {
            res[k++] = n;
        }
        return res;
    }
}

 

posted @ 2019-01-06 17:03  fatttcat  阅读(121)  评论(0编辑  收藏  举报