1. 程式人生 > >leetcode算法:Two Sum II - Input array is sorted

leetcode算法:Two Sum II - Input array is sorted

相加 bsp 滿足 目標 print -s pri ase res

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. Please note that 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.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

這道題描述的是: 給我們一個 非降序的數組 和 一個 目標值 要我們在 數組中 找到兩個數的 索引位置這兩個數滿足 相加的值是目標值 並且 案例保證 一定有唯一的答案。不會出現多個和無解 要求 數組中每個元素只能使用一次 我的思路:
因為答案是唯一的,不會出現多個 也不會沒有 所以省去很多步驟。 我從start(初始為0) 和 last(最後一個位置) 向中間找 如果 相加大於目標 last左移 如果 相加小於目標 start右移 相等的時候 返回 start 和 end 我的python代碼:
 1 class Solution(object):
 2     def twoSum(self, numbers, target):
 3         """
 4         :type numbers: List[int]
 5         :type target: int
 6         :rtype: List[int]
7 """ 8 start, end = 0 , len(numbers) - 1 9 while True: 10 if numbers[start] + numbers[end] > target : 11 end -= 1 12 elif numbers[start] + numbers[end] < target : 13 start += 1 14 else : 15 break 16 return (start+1 , end+1 ) 17 18 19 if __name__ == __main__: 20 s = Solution() 21 res = s.twoSum([2,3,4],6) 22 print(res)

leetcode算法:Two Sum II - Input array is sorted