我是靠谱客的博主 缓慢帽子,这篇文章主要介绍【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%的用户

最后

以上就是缓慢帽子最近收集整理的关于【leetcode】第一题:两数之和(python3)的全部内容,更多相关【leetcode】第一题内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(92)

评论列表共有 0 条评论

立即
投稿
返回
顶部