My java solution that beats 73.8% submissions


  • 0
    T
    public int[] intersect(int[] nums1, int[] nums2) {
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        
        int i=0,j=0;
        int len1 = nums1.length;
        int len2 = nums2.length;
        
        List<Integer> tempList = new ArrayList<>();
        
        while( i<len1 && j<len2 ){
            
            if( nums1[i]<nums2[j] ){
                i++;
            }
            else if( nums1[i]>nums2[j] ){
                j++;
            }
            else{
                tempList.add(nums1[i]);
                i++;
                j++;
            }
        }
        int[] result = new int[tempList.size()];
        int k=0;
        for( int n: tempList ){
            result[k++] = n;
        }
        return result;
    }
    

    follow up question
    1: If the given array is sorted, then there is no need to do arrays.sort() at the beginning. So the complexity will reduced from O(nlogn) to O(n)
    2: Not quite sure what's the meaning of "which algorithm". But if I know which array has smaller length in advance, then in the while loop, I don't need to check both ( use && operation ). I can just use the smaller sized array as my condition for while loop.

    1. Refer to the post here: https://discuss.leetcode.com/topic/45992/solution-to-3rd-follow-up-question/3

Log in to reply
 

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