两数之和 II - 输入有序数组
作者:互联网
var twoSum = function(numbers, target) {
//for循环
for(let i = 0 ; i< numbers.length ; i++){
let j = i + 1;
while(j < numbers.length){
if(numbers[j] + numbers[i] == target){
return [i+1 , j+1]
}
j++
}
}
//双指针
let maxIndex = numbers.length - 1 , minIndex = 0;
while(minIndex < maxIndex){
if(numbers[minIndex] + numbers[maxIndex] < target){
minIndex++
}else if(numbers[minIndex] + numbers[maxIndex] > target){
maxIndex--
}else{
return [minIndex+1,maxIndex+1]
}
}
throw Error('未找到')
};
标签:minIndex,target,maxIndex,II,length,let,numbers,数组,两数 来源: https://blog.csdn.net/weixin_45737062/article/details/122825611