Java solution that beat 98% submission, effective although lengthy


  • 0
    D
    public class Solution {
        public int[] intersection(int[] nums1, int[] nums2) {
           
            if (nums1.length == 0) return nums1;
            if (nums2.length == 0) return nums2;
            Arrays.sort(nums1);
            Arrays.sort(nums2);
            
            List<Integer> list = new ArrayList<Integer>();
            int j = 0;
            
            for (int i =0; i<nums1.length; i++){
               if (i!=0) {
                    if (nums1[i] == nums1[i-1]) continue;
                }
               
    
    
                while ( j<nums2.length){
                    if (nums2[j] == nums1[i]) {
                        list.add(nums2[j]);
    
                        j++;
                        break;
                    }
                    if(nums2[j]>nums1[i]) break;
                    j++;
                }
                
              
                
                
            }
            
            int[] result = new int[list.size()];
            Integer[] temp = list.toArray(new Integer[list.size()]);
            for (int n = 0; n < list.size(); n++) {
                result[n] = temp[n];
            }
        
           
            return result;
        }
    }```

Log in to reply
 

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