javascript O(nlogn) solution


  • 0
    K

    The idea here is iterate over the numbers and for each number take it away from the target to get a diff 'b'. Since the array
    is sorted we can recursively find b as the sort allows to not consider sections of the array.

    var twoSum = function(numbers, target) {
        var j, b, i;
        for(i =0, len = numbers.length; i< len; i++){
            b = target - numbers[i];
            j = findValue(numbers,b, i+1, len);
            if(j !== -1)break;  
        }
        return [i+1, j+1];
    };
    
    function findValue(values, val, i, j){
        var mid = Math.floor((i + j)/2);
        if(values[mid] === val)return mid;
        if(j - i < 2) return -1;
        return (values[mid] > val) ? findValue(values, val, i, mid): findValue(values, val, mid, j)
    }
    

Log in to reply
 

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