2022.08.19
解法1: 暴力循环
Runtime: 4727 ms, faster than 17.45% of Python online submissions for Two Sum.
Memory Usage: 14.5 MB, less than 22.77% of Python online submissions for Two Sum.
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
length = len(nums)
for i in range(length):
for j in range(i+1,length):
if nums[i]+nums[j] == target:
return [i,j]
解法2: 哈希
Runtime: 52 ms, faster than 88.30% of Python online submissions for Two Sum.
Memory Usage: 14.3 MB, less than 68.44% of Python online submissions for Two Sum.
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dic = dict() #利用python中的字典记录每个元素出现的位置,也就是其他语言的哈希表。
for index,value in enumerate(nums): #循环遍历字典中的对象,获得索引和值。
sub = target - value
if sub in dic:
return [dic[sub],index]
else:
dic[value] = index