leetcode-Two sum(最佳思路以及python程式碼實現)
阿新 • • 發佈:2018-12-24
1、Two sum
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
答案:使用hashtable,建立陣列值和下標的鍵值對,在python中相當於使用dict來儲存,dict的key是陣列的值,陣列的下標是dict的value。
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dict = {} # 定義一個字典
for i in xrange(len(nums)): # 遍歷陣列
x = nums[i] # 取當前陣列的值
if target-x in dict: # 如果target減去當前值的差在字典的key中可以找到,直接可以返回dtarget-x對應的值,也即下標
return (dict[target-x], i) # 返回當前下標和找到的下標
dict[x] = i # 將陣列值和下標數存入dict