1.编辑器
我使用的是win10+vscode+leetcode+python3
环境配置参见我的博客:
链接
2.第一百六十七题
(1)题目
英文:
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.
中文:
给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数。
函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2。
说明:
返回的下标值(index1 和 index2)不是从零开始的。
你可以假设每个输入只对应唯一的答案,而且你不可以重复使用相同的元素。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum-ii-input-array-is-sorted
(2)解法
① 双指针法
(耗时:40ms,内存:14.3M)
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
low,high = 0,len(numbers) - 1
while low<high:
if numbers[low] + numbers[high] == target:
return low + 1,high + 1
elif numbers[low] + numbers[high] > target:
high -= 1
else:
low += 1
② 利用顺序先定出上界位置index,节约时间
(耗时:44ms,内存:14.1M)
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
left, right = 0, min(len(numbers) - 1, bisect_right(numbers, target))
while left <= right:
if numbers[left] + numbers[right] < target:
left += 1
elif numbers[left] + numbers[right] > target:
right -= 1
else:
return [left + 1, right + 1]
注意:
1.from bisect import bisect_right。
2.bisect_right返回的是插入的index,如果在原始list中存在,则返回存在元素右边的index。
3.while left <= right:
写成小于也是对的,但是对于特殊情况:
[2,3,5,11]这样return的是[2,2],不和题意
如果是小于号,这种情况就没有return的结果了。