My 6ms simple java solution without HashSet


  • 0
    W
    public class Solution {
        public int[] intersection(int[] nums1, int[] nums2) {
            final int len1;
            final int len2;
            
            if (nums1 == null 
                || (len1 = nums1.length) == 0
                || nums2 == null
                || (len2 = nums2.length) == 0) {
                    return new int[0];
            }
            
            final int[] arr = new int[Math.min(len1, len2)];
            int i = 0, j = 0, count = 0;
            int tmp1, tmp2;
            
            Arrays.sort(nums1);
            Arrays.sort(nums2);
            
            while (i < len1 && j < len2) {
                while (i + 1 < len1 && nums1[i] == nums1[i + 1]) {
                    ++i;
                }
                
                while (j + 1 < len2 && nums2[j] == nums2[j + 1]) {
                    ++j;
                }
                
                tmp1 = nums1[i];
                tmp2 = nums2[j];
                
                if (tmp1 < tmp2) {
                    ++i;
                } else if (tmp2 < tmp1) {
                    ++j;
                } else {
                    arr[count++] = tmp1;
                    ++i;
                    ++j;
                }
            }
            
            final int[] res = new int[count];
            
            if (count == 0) {
                return res;
            }
            
            System.arraycopy(arr, 0, res, 0, count);
            
            return res;
        }
    }
    

Log in to reply
 

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