My java 4ms with sorting solutions


  • 0
    S

    I'm not sure whether or not have the same solution posted here.

    public int[] intersect(int[] nums1, int[] nums2) {
            if(nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0){
            	return new int[0];
            }
            
            //bases on shorter one to fast return
            int[] longer = nums1;
            int[] shorter = nums2;
            if(nums2.length > nums1.length){
            	longer = nums2;
            	shorter = nums1;
            }
            
            //sort the array
            Arrays.sort(longer);
            Arrays.sort(shorter);
            
            List<Integer> l = new ArrayList<>();
            //two pointers
            int p=0,q=0;
            while(p<shorter.length && q<longer.length){
            	if(shorter[p] ==  longer[q]){
            		l.add(shorter[p++]);
            		q++;
            	}else{
            		if(shorter[p] > longer[q]){
            			q++;
            		}else{
            			p++;
            		}
            	}
            }
            
            int[] res = new int[l.size()];
            int i=0;
            for(Integer num : l){
            	res[i++] = num.intValue();
            }
            
            return res;  
        }
    

Log in to reply
 

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