My 5ms Straightforward Java Solution (Without Set)


  • 0
    W
    public int[] intersection(int[] nums1, int[] nums2) {
        if (nums1.length == 0 || nums2.length == 0)
            return new int[0];
        
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        
        int i1 = 0, i2 = 0;
        ArrayList<Integer> list = new ArrayList<Integer>();
        
        while (i1 < nums1.length && i2 < nums2.length) {
            if (nums1[i1] < nums2[i2])
                i1 += 1;
            else if (nums1[i1] > nums2[i2])
                i2 += 1;
            else {
                list.add(nums1[i1]);
            
                try {
                    while (nums1[i1] == nums2[++i2]);
                }
                catch (Exception e) {
                    break;
                }
            }
        }
        
        int result[] = new int[list.size()];
        
        for (int i = 0; i < list.size(); i++)
            result[i] = list.get(i);
        
        return result;
    }

Log in to reply
 

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