Java solution, sorting, O(nlogn). Beats 96% of solutions


  • 0
    M
    public class Solution {
        public int[] intersection(int[] nums1, int[] nums2) {
            if(nums1.length<1 || nums2.length<1){
                return new int[0];
            }
            List<Integer> result = new ArrayList<>();
            Arrays.sort(nums1);
            Arrays.sort(nums2);
            int i=0,j=0;
            while(i<nums1.length && j<nums2.length){
                while(i<nums1.length-1 && nums1[i]==nums1[i+1]){
                    i++;
                }
                while(j<nums2.length-1 && nums2[j]==nums2[j+1]){
                    j++;
                }
                if(nums1[i]==nums2[j]){
                    result.add(nums1[i]);
                    i++;
                    j++;
                }else if(nums1[i] < nums2[j]){
                    i++;
                }else{
                    j++;
                }
            }
            int[] list = new int[result.size()];
            for(i=0; i<list.length; i++){
                list[i] = result.get(i);
            }
            return list;
        }
    }
    

Log in to reply
 

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