leetcode 1. 两数之和
程序员文章站
2022-04-17 17:24:30
...
解法一:
暴力求解
class Solution1:
def twoSum(self, nums, target):
for i in range(len(nums)):
if (target - nums[i]) in nums[i+1:]:
return [i, i + 1 + nums[i+1:].index(target - nums[i])]
# runtime:1072 ms
# memory:14 MB
解法二:
将list的index和value以{value :index}的形式保存在hashmap中,并一边检查是否满足和为target的条件,因为答案唯一,故满足即可退出。(注意重复元素[2, 2] target = 4)
class Solution2:
def twoSum(self, nums, target):
hashmap = {}
for i, num in enumerate(nums):
if target - num in hashmap:
return [hashmap.get(target - num), i]
hashmap[num] = i
# runtime:40 ms
# memory:14.8 MB
下一篇: LeetCode题解——1. 两数之和