Skip to content

Instantly share code, notes, and snippets.

@monsterooo
Created February 13, 2019 14:03
Show Gist options
  • Save monsterooo/8c3e6f29bbfd848d95ea7e3126eb0fa2 to your computer and use it in GitHub Desktop.
Save monsterooo/8c3e6f29bbfd848d95ea7e3126eb0fa2 to your computer and use it in GitHub Desktop.
算法练习-有序数组中求和为给定值得两个数
var nums = [1,2,3,6,8,11];
var target = 10;
function getTwoNumSum(nums, target) {
var i = 0, j = nums.length - 1;
while(i < j) {
if (nums[i] + nums[j] > target) {
j--;
} else if (nums[i] + nums[j] < target) {
i++;
} else {
return [i + 1, j + 1];
}
}
return [-1, -1];
}
console.log('最终值为 > ', getTwoNumSum(nums, target));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment