4 ms JAVA solution. Sort two arrays first.


  • 0
    B
    public class Solution {
        public int[] intersect(int[] nums1, int[] nums2) {
            Arrays.sort(nums1);
            Arrays.sort(nums2);
            int i = 0, j = 0;
            int[] resultTmp = new int[Math.min(nums1.length, nums2.length)];
            int idx = 0;
            while(i < nums1.length && j < nums2.length){
                if(nums1[i] < nums2[j]) i++;
                else if (nums1[i] > nums2[j]) j++;
                else if (nums1[i] == nums2[j]){
                    resultTmp[idx] = nums1[i];
                    i++;
                    j++;
                    idx++;
                }
            }
            int[] result = new int[idx];
            System.arraycopy(resultTmp, 0, result, 0, idx);
            return result;
        }
    }
    

Log in to reply
 

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