LeetCode 350. Intersection of Two Arrays II

it’s the follow up of LC349, which we don’t allows any duplicates in the final results.
but now we need to make the duplicate appears the exactly same times with our original arrays.

idea:
of course we can sort both of them and use two pointers to solve this problem.
and also, in order to save some space, we can do it in place on nums1 or nums2

//this can be easily solved in brute force
//use two poiter, this is easy

//we know this problem is a follow up of LC349, which both array contains unqiue elements
//and my solution for this problem can also be used to solve LC349

//however, we can improve the space complexity. we can overwrite any one of nums1 or nums2. becasue intersect will never exceed Math.min(nums1.length, nums2.length)

//another way is to use hashmap, which is to store one of array in hashmap, and check another one char each time, if map contains this key, then add it to final results. the correspnding value minus 1

//follow up 3 is pretty interesting, what if some of those two arrays can't fit into memory at once? if only one can fit, then we tranfer it into hashmap
//if both of them can't fit, hashmap way and sort way are still can be used, just needs to be modified
//for hashmap way, we count the subarrays and add them up.
//for sort way, we can use external sort(merge sort and selection are both external sort)
class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        if (nums1 == null || nums2 == null) return null;
        
        
        int m = nums1.length;
        int n = nums2.length;
        if (m == 0 || n == 0) {
            return new int[0];
        }
        
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        int i = 0;
        int j = 0;
        //List<Integer> list = new ArrayList<>();
        int k = 0;
        while (i < m && j < n) {
            if (nums1[i] == nums2[j]) {
                nums1[k] = nums1[i];
                k++;
                i++;
                j++;
            } else if (nums1[i] > nums2[j]) {
                j++;
            } else if (nums1[i] < nums2[j]) {
                i++;
            }
        }
        
        
        return Arrays.copyOfRange(nums1, 0, k);
    }
}

but how can we solve this problem using binary search?

posted @ 2020-11-11 11:05  EvanMeetTheWorld  阅读(35)  评论(0)    收藏  举报