Java: sort and two pointers concise solution


  • 0
    J

    For this one, we can use two pointers.
    We sort the two arrays first, then move two pointers based on the two values comparison. If two values are the same, bother pointers increase one. If one is smaller than another one, increase the pointer of the smaller one.

     public int[] intersect(int[] nums1, int[] nums2) {
            ArrayList<Integer> resultArray = new ArrayList<>();
            if(nums1 == null || nums2 == null || nums1.length == 0 || nums2.length == 0) return new int[0];
            int index1 = 0, index2 = 0;
            Arrays.sort(nums1);
            Arrays.sort(nums2);
            
            while(index1 < nums1.length && index2 < nums2.length){
                    if(nums1[index1] == nums2[index2]){
                        resultArray.add(nums1[index1]);
                        index1++;
                        index2++;
                    }else if(nums1[index1] < nums2[index2]){
                        index1++;
                    }else{
                        index2++;
                    }
            }
            
            int index = 0;
            int[] result = new int[resultArray.size()];
            for(int num : resultArray){
                result[index++] = num;
            }
            return result;
        }

Log in to reply
 

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