LeetCode - Intersection of Two Arrays II

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

For example:
given nums1  =  nums2  =  , return  . [1, 2, 2, 1][2, 2][2, 2]

Notice:

  •    The number of occurrences of each element in the output should be the same as the number of occurrences of the element in the two arrays.
  •    We can ignore the order of output results.

follow up:

  • What if the given array is already sorted? How would you optimize your algorithm?
  • If  the size of nums1  is much smaller than  nums2  , which method is better?

  • If the elements of nums2 are stored on disk and memory is limited, you can't load all the elements into memory at once, what should you do?
  • Solution 1

    It is used toMap establish nums1the mapping between the characters in and the number of its occurrences, and then traverse the nums2array. If Mapthe number of the current character in is greater than 0, add this character to the result res, and then Mapthe corresponding value is decremented by 1.

    public int[] intersect(int[] nums1, int[] nums2) {
    
        List<Integer> tmp = new ArrayList<>();
    
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
    
        for (int i = 0; i < nums1.length; i++) {
            Integer value = map.get(nums1[i]);
            map.put(nums1[i], (value == null ? 0 : value) + 1);
        }
    
        for (int i = 0; i < nums2.length; i++) {
            if (map.containsKey(nums2[i]) && map.get(nums2[i]) != 0) {
                tmp.add(nums2[i]);
                map.put(nums2[i], map.get(nums2[i]) - 1);
            }
        }
    
        int[] result = new int[tmp.size()];
        int i = 0;
        for (Integer e : tmp)
            result[i++] = e;
        return result;
    }

    Solution 2

    Sort the two arrays, and then use the two indices to represent the starting positions of the two arrays. If the numbers represented by the two indices are equal, the numbers are stored in the result, and both indices are incremented by 1. If the number represented by the first index is larger, the second index is incremented by 1, and vice versa.

    public int[] intersect(int[] nums1, int[] nums2) {
    
        Arrays.sort(nums1);
        Arrays.sort(nums2);
    
        List<Integer> tmp = new ArrayList<>();
    
        int i = 0;
        int j = 0;
        while (i < nums1.length && j < nums2.length) {
            if (nums2[j] > nums1[i]) {
                i++;
            } else if (nums2[j] < nums1[i]) {
                j++;
            } else {
                tmp.add(nums1[i]);
                i++;
                j++;
            }
        }
    
        int[] result = new int[tmp.size()];
        for (int k = 0; k < result.length; k++) {
            result[k] = tmp.get(k);
        }
        return result;
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325949234&siteId=291194637