167. Two Sum II - Input Array Is Sorted
給定一個從1開始索引的整數數組 numbers,該數組已經按非遞減順序排序,找到兩個數,使它們的和等於一個特定的目標數 target。讓這兩個數分別是 numbers[index1] 和 numbers[index2],其中 1 <= index1 < index2 <= numbers.length。
返回這兩個數的索引值 index1 和 index2,並將其加一作為一個長度為2的整數數組 [index1, index2]。
測試用例保證只有一個解決方案。你不能重複使用相同的元素。
你的解決方案必須只使用常數額外空間。
範例 :
輸入:numbers = [2,7,11,15], target = 9
輸出:[1,2]
解釋:2 和 7 的和是 9。因此,index1 = 1,index2 = 2。我們返回 [1, 2]。
Python
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
left, right = 0, len(numbers) - 1
while left < right:
current_sum = numbers[left] + numbers[right]
if current_sum == target:
return [left + 1, right + 1]
elif current_sum < target:
left += 1
else:
right -= 1
return []
17.68MB, 95ms
C++
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
int left = 0, right = numbers.size() - 1;
while (left < right) {
int sum = numbers[left] + numbers[right];
if (sum == target) {
return {left + 1, right + 1}; // Return 1-based indices
} else if (sum < target) {
left++;
} else {
right--;
}
}
return {}; // In case there is no solution, although the problem guarantees there is one
}
};
17.88MB, 7ms
Javascript
/**
* @param {number[]} numbers
* @param {number} target
* @return {number[]}
*/
var twoSum = function(numbers, target) {
let left = 0, right = numbers.length - 1;
while (left < right) {
let sum = numbers[left] + numbers[right];
if (sum === target) {
return [left + 1, right + 1]; // Return 1-based indices
} else if (sum < target) {
left++;
} else {
right--;
}
}
return []; // In case there is no solution, although the problem guarantees there is one
};
50.05MB, 58ms