問題
原文
Given a 1-indexed array of integers
numbers
that is already sorted in non-decreasing order, find two numbers such that they add up to a specifictarget
number. Let these two numbers benumbers[index1]
andnumbers[index2]
where1 <= index1 < index2 <= numbers.length
.Return the indices of the two numbers,
index1
andindex2
, added by one as an integer array[index1, index2]
of length 2.The tests are generated such that there is exactly one solution. You may not use the same element twice.
Your solution must use only constant extra space.
Example 1:
123 Input: numbers = [<u>2</u>,<u>7</u>,11,15], target = 9Output: [1,2]Explanation: The sum of 2 and 7 is 9. Therefore, index<sub>1</sub> = 1, index<sub>2</sub> = 2. We return [1, 2].Example 2:
123 Input: numbers = [<u>2</u>,3,<u>4</u>], target = 6Output: [1,3]Explanation: The sum of 2 and 4 is 6. Therefore index<sub>1</sub> = 1, index<sub>2</sub> = 3. We return [1, 3].Example 3:
123 Input: numbers = [<u>-1</u>,<u>0</u>], target = -1Output: [1,2]Explanation: The sum of -1 and 0 is -1. Therefore index<sub>1</sub> = 1, index<sub>2</sub> = 2. We return [1, 2].
Constraints:
2 <= numbers.length <= 3 * 104
-1000 <= numbers[i] <= 1000
numbers
is sorted in non-decreasing order.-1000 <= target <= 1000
- The tests are generated such that there is exactly one solution.
内容
※正しくない可能性があります。
解答
解答1:two pointer
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: #左右のポインタを用意 l,r = 0, len(numbers)-1 #左のポインタが右のポインタの左側にある限り繰り返す while l<r: #左ポインタが指す要素と右ポインタが指す要素の合計をsに代入 s = numbers[l] + numbers[r] #sがtaretと一致した場合 if s== target: #返す return [l+1, r+1] #sがtarget未満の場合 elif s < target: #左ポインタを進める l += 1 #sがtarget以上の場合 else: #右ポインタを左に進める r -= 1 |
解答2:ハッシュテーブル(辞書)
解答3:二分探索
補足・参考・感想
■補足
■参考
■感想
コメント