日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

two sum python_Python | Leetcode 之 Two Sum

發布時間:2024/8/23 python 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。