题目链接: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%的用户