167. Two Sum II - Input array is sorted
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.
My idea:先找出这个target的大致位置,用迭代比大小确定,然后再用迭代逐个相加
class Solution: def twoSum(self, numbers,target): i = 0 while (numbers[i] < target): i = i + 1 if(max(numbers)<=target): i=len(numbers)-1 break if(i==0): return [1,2] b = 1 flag = 0 c = [] for a in range(i): while (flag == 0 ): if (numbers[a] + numbers[b] == target): flag = 1 c.append(a + 1) c.append(b + 1) return c b = b + 1 if(b >i): break b=a+2 return c
你以为这样就结束了?
不,这样耗时太长,所以失败了。。。因为碰到了一个2500char的测试用例
而且这样写要考虑的情况太多,不简便,不推荐。
其实学的就是双指针,所以直接双指针就完事了。。
class Solution: def twoSum(self, numbers,target): a=0 b=len(numbers)-1 while(a<b): if(numbers[a]+numbers[b]==target): c=[a+1,b+1] return c elif(numbers[a]+numbers[b]<target): a=a+1 else: b=b-1
执行用时 : 60 ms, 在Two Sum II - Input array is sorted的Python3提交中击败了62.54% 的用户
内存消耗 : 13.4 MB, 在Two Sum II - Input array is sorted的Python3提交中击败了95.42% 的用户
posted on 2019-05-06 22:00 imyourterminal 阅读(110) 评论(0) 编辑 收藏 举报