难度: Easy
原题连接
内容描述
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.
思路 1 - 时间复杂度: O(lgN) - 空间复杂度: O(1)
二分法+双指针,beats 95.15%
因为答案唯一,符合要求return即可
class Solution(object):
def twoSum(self, numbers, target):
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
r, lens = 0, len(numbers) - 1
while r < lens:
if numbers[r] + numbers[lens] == target:
return [r+1, lens+1]
elif numbers[r] + numbers[lens] < target:
r += 1
else:
lens -= 1总结:
- 此题和001题很类似,区别在与此题参数为有序数组,并且返回的index+1