Java Solution within 4ms


  • 0
    A
    public class Solution {
        public int[] intersect(int[] nums1, int[] nums2)
        {
            List<Integer> result = new ArrayList<>();
    
            Arrays.sort(nums1);
            Arrays.sort(nums2);
    
            int i = 0, j = 0;
            while(i < nums1.length && j < nums2.length)
            {
                while(nums1[i] < nums2[j])
                {
                    i++;
                    if(i == nums1.length) break;
                }
                if(i >= nums1.length || j >= nums2.length) break;
                while(nums1[i] > nums2[j])
                {
                    j++;
                    if(j == nums2.length) break;
                }
                if(i >= nums1.length || j >= nums2.length) break;
    
                if(nums1[i] == nums2[j])
                {
                    result.add(nums1[i]);
                    i++; j++;
                }
            }
    
            int size = result.size();
            int[] resultArray = new int[size];
    
            for(int cao = 0; cao < size; cao++)
            {
                resultArray[cao] = result.get(cao);
            }
            return resultArray;
        }
    }
    

    I believe my code is kind of redundant somewhere...but I don't know how to make it smarter.
    Glad to hear your advice! thx


  • 0
    A

    I think two small while loops in your code seems a kind of redundant. Also, after i++ or j++, you don't need to write 'if' to check whether i or j is equals to array length. Since, the whole while loop "while(i < nums1.length && j < nums2.length)" makes sure that if i,j reach those values, loop will break. Replace code in outermost loop with following statements will make your code more brief:

    	 	    if(nums1[i]<nums2[j]){
    	 	        i++;
    	 	    }
    	 	    else if(nums1[i]>nums2[j]){
    	 	        j++;
    	 	    }
    	 	    else{
    	 	        result.add(nums2[j++]); 
    	 	        i++;
    	 	    }
    

Log in to reply
 

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