two sum python_Python | Leetcode 之 Two Sum
說來慚愧,到現在才開始刷Leetcode,但遲到總比不到好。
題目: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 sameelement twice.
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
先上暴力解法:
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
length = len(nums)
for i in range(length) :
for j in range(length):
if nums[i] == target - nums[j] and i != j:
return [i, j]
Submit看結果:
Runtime: 7780 ms, faster than 5.01% of Python3 online submissions for Two Sum.
Memory Usage: 13.8 MB, less than 24.07% of Python3 online submissions for Two Sum.
即使是第一道題,但這結果也太差了吧
兩個for循環做了無用功,如果把list分成兩部分來計算,也就是只用for循環一次呢?
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
k = 0
for i in nums:
k += 1
if target - i in nums[k:]:
return(k -1, nums[k:].index(target - i) + k)
Submit看結果:
Runtime: 848 ms,faster than32.81%ofPython3online submissions forTwo Sum.
仍舊是連一半都沒超過啊,娘匹西。
官方方法 Two-Pass Hash Table
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
hashTable = {}
length = len(nums)
for i in range(length):
hashTable[nums[i]] = i
for i in range(length):
if target - nums[i] in hashTable and hashTable[target - nums[i]] != i:
return [i, hashTable[target - nums[i]]]
return([])
Submit看結果:
Runtime: 48 ms, faster than58.71%ofPython3online submissions forTwo Sum.
官方還提供One-Pass Hash Table,也就是每次插入一個元素,然后檢查這個元素是否符合,以此類推。
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
hashTable = {}
for i, num in enumerate(nums):
if target - num in hashTable:
return([hashTable[target - num], i])
break
hashTable[num] = i
return([])
但這個結果submit的結果并沒有表現得如官方所說的那樣。
總結:結果這個問題的方法有很多,從暴力到哈希表,除了要熟知基本的元素操作,便是懂得時間復雜度和空間復雜度的一個balance
關于Python語法的細節還是要加強,不然卡住的地方太多了
哈希表的概念要再加強一些
總結
以上是生活随笔為你收集整理的two sum python_Python | Leetcode 之 Two Sum的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: spi四种工作模式时序图_还没学会SPI
- 下一篇: 嫦娥回来了,还有哪些浪漫传说已经实现?