【leetcode】第一題:兩數之和(python3)

題目鏈接:https://leetcode-cn.com/problems/two-sum/

暴力破解:

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        delValue = 0
        for i in range(len(nums)):
            delValue = target - nums[i]
            if delValue in nums and nums.index(delValue) != i:
                return [i, nums.index(delValue)]

執行用時 :1480 ms, 在所有 Python3 提交中擊敗了24.22%的用戶

內存消耗 :14.6 MB, 在所有 Python3 提交中擊敗了13.41%的用戶

使用字典:

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        delValue = 0
        delDict = {}
        for i in range(len(nums)):
            delValue = target - nums[i]
            if delValue in delDict:
                return [delDict[delValue], i]
            else:
                delDict[nums[i]] = i

執行用時 :60 ms, 在所有 Python3 提交中擊敗了58.00%的用戶

內存消耗 :15.2 MB, 在所有 Python3 提交中擊敗了5.48%的用戶

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章