1. 程式人生 > >Leetcode 167. 兩數之和 II - 輸入有序數組 By Python

Leetcode 167. 兩數之和 II - 輸入有序數組 By Python

目標 .cn 一個 bject strong 輸入 {} 不可 tar

給定一個已按照升序排列 的有序數組,找到兩個數使得它們相加之和等於目標數。

函數應該返回這兩個下標值 index1 和 index2,其中 index1 必須小於 index2

說明:

  • 返回的下標值(index1 和 index2)不是從零開始的。
  • 你可以假設每個輸入只對應唯一的答案,而且你不可以重復使用相同的元素。

示例:

輸入: numbers = [2, 7, 11, 15], target = 9
輸出: [1,2]
解釋: 2 與 7 之和等於目標數 9 。因此 index1 = 1, index2 = 2 。

思路

如果是二重循環枚舉會超時,可以換個思路,把加法變為減法,跟另一題兩數之和差不多https://www.cnblogs.com/MartinLwx/p/9679029.html

代碼

class Solution(object):
    def twoSum(self, numbers, target):
        """
        :type numbers: List[int]
        :type target: int
        :rtype: List[int]
        """
        d = {}
        for key,value in enumerate(numbers):
            if value not in d:
                delta = target - value      #比如題中的數據,當value為2的時候得到應有的差值為7
                d[delta] = key      #7對應配對的key存儲在d[delta]中
            else:       #已經在字典裏說明前面已經出現了一個可以配對的值
                return [d[value]+1, key+1]

Leetcode 167. 兩數之和 II - 輸入有序數組 By Python