?文章來源地址http://www.zghlxwxcb.cn/news/detail-585970.html
給你一個(gè)下標(biāo)從?1?開始的整數(shù)數(shù)組?numbers
?,該數(shù)組已按?非遞減順序排列??,請(qǐng)你從數(shù)組中找出滿足相加之和等于目標(biāo)數(shù)?target
?的兩個(gè)數(shù)。如果設(shè)這兩個(gè)數(shù)分別是?numbers[index1]
?和?numbers[index2]
?,則?1 <= index1 < index2 <= numbers.length
?。
以長(zhǎng)度為 2 的整數(shù)數(shù)組?[index1, index2]
?的形式返回這兩個(gè)整數(shù)的下標(biāo)?index1
?和?index2
。
你可以假設(shè)每個(gè)輸入?只對(duì)應(yīng)唯一的答案?,而且你?不可以?重復(fù)使用相同的元素。
你所設(shè)計(jì)的解決方案必須只使用常量級(jí)的額外空間。
?
示例 1:
輸入:numbers = [2,7,11,15], target = 9 輸出:[1,2] 解釋:2 與 7 之和等于目標(biāo)數(shù) 9 。因此 index1 = 1, index2 = 2 。返回 [1, 2] 。
示例 2:
輸入:numbers = [2,3,4], target = 6 輸出:[1,3] 解釋:2 與 4 之和等于目標(biāo)數(shù) 6 。因此 index1 = 1, index2 = 3 。返回 [1, 3] 。
示例 3:
輸入:numbers = [-1,0], target = -1 輸出:[1,2] 解釋:-1 與 0 之和等于目標(biāo)數(shù) -1 。因此 index1 = 1, index2 = 2 。返回 [1, 2] 。
?
提示:
2 <= numbers.length <= 3 * 104
-1000 <= numbers[i] <= 1000
-
numbers
?按?非遞減順序?排列 -1000 <= target <= 1000
- 僅存在一個(gè)有效答案
-
class Solution { public: vector<int> twoSum(vector<int>& numbers, int target) { //雙指針,滑動(dòng)窗口 int n=numbers.size(); int l=0,r=n-1; while(l<r){ int sum=numbers[l]+numbers[r]; if(sum==target){ //vector<int>可以刪除,空間換時(shí)間 return vector<int>{l+1,r+1}; } else if(sum<target){ l++; } else{ r--; } } return vector<int>{-1,-1}; } };
?文章來源:http://www.zghlxwxcb.cn/news/detail-585970.html
?
到了這里,關(guān)于167. 兩數(shù)之和 II - 輸入有序數(shù)組的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!