leetcode 每日一题 1.两数之和

暴力法

思路:

循环枚举出所有可能。

代码:

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        for i in range(len(nums)):
            for j in range(i+1,len(nums)):
                if nums[i]+nums[j] == target:
                    return [i,j]
        return []

哈希表

思路:

创建一个hash表,将数组中的元素值作为key,下标作为value。遍历数组时,只需要查看target减去当前元素值所得到的值作为key是否在hash表中出现过即可。

代码:

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        hashmap = {}
        for index,num in enumerate(nums):
            remianNum = target - num
            if remianNum in hashmap:
                return [hashmap[remianNum],index]
            hashmap[num] = index
        return []

 

posted @ 2020-04-14 11:58  nil_f  阅读(84)  评论(0)    收藏  举报