JAVA O(n) solution with HashMap & O(nlogn) solution with merge sort idea


  • 2

    Here come two solutions based on Java.

    1. Using HashMap to record and find out the duplicate part, O(n) time and O(n) space.
    public int[] intersect(int[] nums1, int[] nums2) {
        Map<Integer, Integer> map = new HashMap<>();
        List<Integer> temp = new ArrayList<Integer>();
        for (int num : nums1)
            map.put(num, map.getOrDefault(num, 0)+1);
        for (int num : nums2){
            if (map.containsKey(num) && map.get(num) > 0){
                temp.add(num);
                map.put(num, map.get(num)-1);
            }
        }
        int[] res = new int[temp.size()];
        for (int i = 0; i < temp.size(); i++)
            res[i] = temp.get(i);
        return res;
    }
    
    1. Using Merge Sort idea, O(nlogn) time and O(1) space.
    public int[] intersect(int[] nums1, int[] nums2) {
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        List<Integer> temp = new ArrayList<Integer>();
        for (int i = 0, j = 0; i < nums1.length && j < nums2.length;){
            if (nums1[i] < nums2[j]) i++;
            else if (nums1[i] > nums2[j]) j++;
            else {
                temp.add(nums1[i]);
                i++; j++;
            }
        }
        int[] res = new int[temp.size()];
        for (int i = 0; i < temp.size(); i++)
            res[i] = temp.get(i);
        return res;
    }

  • 0
    R

    good solution


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.