3ms Java code


  • 0
    V

    public int[] intersect(int[] nums1, int[] nums2)
    {
    int len1= nums1.length;
    int len2 = nums2.length;

        int result[] = new int[(len1>len2)?len1:len2];
        int index1=0;
        int index2=0;
        int i=0;
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        while(index1<len1 && index2<len2)
        {
            if(nums1[index1]==nums2[index2])
            {
                result[i++]=nums2[index2];
                index1++;
                index2++;
            }
            else if(nums1[index1]<nums2[index2])
            {
                index1++;
            }
            else
                index2++;
        }
        return Arrays.copyOf(result,i);
    }

Log in to reply
 

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