JavaScript with binary search & sort numbers


  • 0
    V
    function sortNums(a, b) {
        return a -b;
    }
    var intersection = function(nums1, nums2) {
        var result = [];
        var bigArr, smallArr;
        nums1.sort(sortNums);
        nums2.sort(sortNums);
        if(nums1.length > nums2.length){
            bigArr = nums1;
            smallArr = nums2;
        } else {
            bigArr = nums2;
            smallArr = nums1;
        }
        var i;
        var flag1 = false;
        var flag2 = false;
        for(i = 0; i < smallArr.length; i++) {
            flag1 = bs(bigArr, smallArr[i]);
            flag2 = bs(result, smallArr[i]);
            if(flag1 && !flag2) {
                result.push(smallArr[i]);
            }
        }
        return result;
    };
    
    var bs = function(arr, num) {
        var low = 0;
        var high = arr.length - 1;
        var mid;
        while(low <= high) {
            mid = (low + high)/2 | 0 //or (low + high) >> 1;
            if(num > arr[mid]) {
                low = mid + 1;
            }else if(num < arr[mid]){
                high = mid - 1;
            }else {
                return true;
            }
        }
        return false;
    }
    

Log in to reply
 

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