350. Intersection of Two Arrays II (Easy)

https://leetcode.com/problems/intersection-of-two-arrays-ii/

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

Example 1:

Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]

Example 2:

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]

Note:

  • Each element in the result should appear as many times as it shows in both arrays.
  • The result can be in any order.

Follow up:

  • What if the given array is already sorted? How would you optimize your algorithm?
  • What if nums1's size is small compared to nums2's size? Which algorithm is better?
  • What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?

Hints

Solutions

public class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        int i = 0, j = 0;
        ArrayList<Integer> arr = new ArrayList<>();
        while(i < nums1.length && j < nums2.length) {
            if(nums1[i] == nums2[j]) {
                arr.add(nums1[i]);
                i++;
                j++;
            } else if(nums1[i] > nums2[j]) {
                j++;
            } else {
                i++;
            }
        }

        /*
        HashMap<Integer, Integer> map = new HashMap<>();
        for(int i = 0;i < nums1.length;++i) {
            map.put(nums1[i], map.getOrDefault(nums1[i], 0) + 1);
        }

        ArrayList<Integer> arr = new ArrayList<>();
        for(int i = 0;i < nums2.length;++i) {
            if(map.containsKey(nums2[i])) {
                int count = map.get(nums2[i]);
                if(count > 0) {
                    arr.add(nums2[i]);
                    count--;
                    if(count == 0) map.remove(nums2[i]);
                    else map.put(nums2[i], count);
                }
            }
        }*/

        int[] res = new int[arr.size()];
        for(i = 0;i < arr.size();++i) {
            res[i] = arr.get(i);
        }

        return res;
    }
}
Copyright © iovi.com 2017 all right reserved,powered by GitbookLast Modification: 2019-04-15 19:25:40

results matching ""

    No results matching ""