4ms JAVA Solution With 2 pointers and sort


  • 0
    Y
    public class Solution {
        public int[] intersection(int[] nums1, int[] nums2) {
            int[] res = new int[0];
            if(nums1.length == 0 || nums2.length == 0)
                return res;
            Arrays.sort(nums1);
            Arrays.sort(nums2);
            int[] longArray = nums1.length > nums2.length ? nums1 : nums2;
            int[] shortArray = nums1.length <= nums2.length ? nums1 : nums2;
            List<Integer> list = new ArrayList<Integer>();
            int index = 0;
            for(int i=0; i<longArray.length; i++){
                while(index < shortArray.length && longArray[i] > shortArray[index]) index++;
                if(index >= shortArray.length)
                    break;
                if(longArray[i] == shortArray[index]){
                    list.add(shortArray[index++]);
                    while(index < shortArray.length && shortArray[index] == shortArray[index-1]) index++;
                }
            }
            res = new int[list.size()];
            for(int i=0; i<list.size(); i++){
                res[i] = list.get(i);
            }
            return res;
        }
    }
    

Log in to reply
 

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