1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
|
var twoSum = function(numbers, target) { for(let i = 0;i<numbers.length-1;i++) for(let j = i+1;j<numbers.length;j++) if(numbers[i] + numbers[j] === target) return [i+1,j+1] };
var twoSum = function(numbers, target) { for(let i = 0;i < numbers.length-1;i++){ let t = target - numbers[i] let l = i+1, r = numbers.length-1 while(l <= r){ let mid = l + ((r-l) >> 1) if(numbers[mid] === t) return [i + 1, mid + 1] else if(numbers[mid] < t) l = mid+1 else r = mid-1 } } };
var twoSum = function(numbers, target) { let l = 0,r = numbers.length - 1 while(l < r){ if(numbers[l] + numbers[r] === target) return [l+1,r+1] else if(numbers[l] + numbers[r] < target) l++ else r-- } };
|