難度: Easygit
刷題內容 原題鏈接leetcode-twosumgithub
內容描述apache
Given an array of integers, return indices of the two numbers such that they add up to a specific target.數組
You may assume that each input would have exactly one solution, and you may not use the same element twice.bash
Example:函數
Given nums = [2, 7, 11, 15], target = 9,ui
Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].spa
1.兩個總和 簡單 給定一個整數數組,返回兩個數字的索引,使它們相加到特定目標。翻譯
您能夠假設每一個輸入只有一個解決方案,而且您可能不會兩次使用相同的元素。code
例:
被給NUMS = [2,7,11,15],目標變量TARGET = 9,
由於NUMS[0] + NUMS[1] = 2 + 7 = 9,
則返回[0,1]。
思路一:最直接想到的就是分別線性遍歷一遍,不過期間複雜度: O(N^2)- 空間複雜度: O(1)******
class Solution(object):
def twoSum(self, nums, target):
""" :type nums: List[int] :type target: int :rtype: List[int] """
for i in range(len(nums)):
for j in range(i+1, len(nums)):
if nums[i] + nums[j] == target:
return [i, j]
複製代碼
很顯然上面對時間要求太多,能夠犧牲空間換時間
思路二:時間複雜度: O(N)- 空間複雜度: O(N)******
class Solution(object):
def twoSum(self, nums, target):
""" :type nums: List[int] :type target: int :rtype: List[int] """
lookup = {}
for i, num in enumerate(nums):
if target - num in lookup:
return [lookup[target-num], i]
else:
lookup[num] = i
複製代碼
class Solution(object):
def twoSum(self, nums, target):
""" :type nums: List[int] :type target: int :rtype: List[int] """
lookup = {}
for i, num in enumerate(nums):
print("序號變量i :{i} 數值變量num :{num}".format(i=i,num=num))
if target - num in lookup:
print("返回找到的兩個數的索引值列表:{}".format([lookup[target-num], i]))
else:
lookup[num] = i
print("字典lookup:{}".format(lookup))
S = Solution()
nums = [2,7,13,11]
target = 9
S.twoSum(nums,target)
# 如下是 enumerate() 方法的語法:
#
# enumerate(sequence, [start=0])
# 參數
# sequence -- 一個序列、迭代器或其餘支持迭代對象。
# start -- 下標起始位置。
# 返回值
# 返回 enumerate(枚舉) 對象。
#
# 實例
# 如下展現了使用 enumerate() 方法的實例:
#
# >>>seasons = ['Spring', 'Summer', 'Fall', 'Winter']
# >>> list(enumerate(seasons))
# [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
# >>> list(enumerate(seasons, start=1)) # 下標從 1 開始
# [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
複製代碼