Simple O(nlogn) solution that runs in 4ms


  • 0
    E

    public class Solution {

    public int[] intersection(int[] nums1, int[] nums2) {

    java.util.Arrays.sort(nums1);

    java.util.Arrays.sort(nums2);

    List<Integer> res = new ArrayList<>();

        int i = 0, j = 0;
        while (i != nums1.length && j != nums2.length)
            if (nums1[i] == nums2[j]) {
                res.add(nums1[i]);
                while (++i != nums1.length && nums1[i] == nums1[i - 1]);
                while (++j != nums2.length && nums2[j] == nums2[j - 1]);
            } else if (nums1[i] < nums2[j])
                i++;
            else
                j++;
        int[] ans = new int[res.size()];
        for (i = 0; i < ans.length; i++)
            ans[i] = res.get(i);
        return ans;
    }
    

    }


Log in to reply
 

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