4ms, using Arrays


  • 0

    Java Arrays is a wealth of useful functions.

    public class Solution {
        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[] longArray, shortArray;
            
            if(nums1.length < nums2.length){
                shortArray = nums1;
                longArray = nums2;
            }else{
                shortArray = nums2;
                longArray = nums1;
            }
            
            int idx = 0;
            int[] out_array = new int[shortArray.length]; 
            for(int i=0;i<shortArray.length; i++){
                int search_idx = Arrays.binarySearch(longArray,
                                                  shortArray[i]);
                if(search_idx < 0)continue;
                if(idx == 0){
                    out_array[idx++] = longArray[search_idx];
                }else if(out_array[idx-1] != longArray[search_idx]){
                    out_array[idx++] = longArray[search_idx];
                }          
            }          
    
            return Arrays.copyOf(out_array, idx);
        }
    }
    

Log in to reply
 

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