Python leetcode #1 Two Sum

来源:互联网 发布:域名赎回期 编辑:程序博客网 时间:2024/05/21 17:54

leetcode #1 Two Sum


首先要记住不能用双层for循环暴力破解,这样时间复杂度为O(n2)太高了受不鸟。所以先用一次循环把所有的数存到字典中,key为列表中的数,value为索引。然后在判断字典中的值有没有,用target-num计算出结果的索引。要记住记得判断nums = [3, 3], target = 6这种特殊情况。这样子的时间复杂度只有O(n)就快很多了。

class Solution(object):    def twoSum(self, nums, target):        """        :type nums: List[int]        :type target: int        :rtype: List[int]        """        d = {}        num = 0        while num < len(nums):            if not nums[num] in d:                d[nums[num]] = num            if target - nums[num] in d:                if d[target - nums[num]] < num:                    return [d[target - nums[num]], num]            num += 1
0 0