LeetCode 0167. Two Sum II - Input array is sorted兩數(shù)之和 II - 輸入有序數(shù)組【Easy】【Python】【雙指針】
題目
Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.
Note:
- Your returned answers (both index1 and index2) are not zero-based.
- You may assume that each input would have exactly one solution and you may not use the same element twice.
Example:
Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
翻譯
給定一個(gè)已按照升序排列 的有序數(shù)組朽寞,找到兩個(gè)數(shù)使得它們相加之和等于目標(biāo)數(shù)斩郎。
函數(shù)應(yīng)該返回這兩個(gè)下標(biāo)值 index1 和 index2缩宜,其中 index1 必須小于 index2。
說(shuō)明:
返回的下標(biāo)值(index1 和 index2)不是從零開(kāi)始的妓布。
你可以假設(shè)每個(gè)輸入只對(duì)應(yīng)唯一的答案匣沼,而且你不可以重復(fù)使用相同的元素捂龄。
示例:
輸入: numbers = [2, 7, 11, 15], target = 9
輸出: [1,2]
解釋: 2 與 7 之和等于目標(biāo)數(shù) 9 。因此 index1 = 1, index2 = 2 唇撬。
思路
雙指針
left 指針從頭指向尾展融,right 指針從尾指向頭,然后判斷兩數(shù)之和是否等于 target扑浸。
時(shí)間復(fù)雜度:O(n)
Python代碼
class Solution(object):
def twoSum(self, numbers, target):
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
left = 0 # 從頭指向尾
right = len(numbers) - 1 # 從尾指向頭
while left < right:
if numbers[left] + numbers[right] == target:
return [left + 1, right + 1]
elif numbers[left] + numbers[right] > target:
right -= 1
else:
left += 1
return []