欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

leetcode 1. 两数之和

程序员文章站 2022-04-17 17:24:30
...

leeetcode 1.两数之和
leetcode 1. 两数之和

解法一:
暴力求解

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-python