importGPX

LeetCode 1.两数之和(python)

1、朴素解法

最朴素的两个for循环大法:

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]

但注意,不要用enumerate函数写,会超时:

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        size = len(nums)
        for i, m in enumerate(nums):
            j = i+1
            while j < size :
                if nums[i] + nums[j] == target:
                    return [i, j]
                else:
                    j+=1

2、用 in 优化(一遍for循环?)

python大法好:用in方法,只需要一个for循环就能解决问题了(但其实是python的in帮我们做了一个查找的循环)

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

3、用python字典(哈希表的算法思想)

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        d = {}
        for i in range(len(nums)):
            a = target - nums[i]
            if nums[i] in d:
                return d[nums[i]],i
            else:
                d[a] = i

自己想想写写就明白了,字典d里键值对 {k:v}的含义是,与k能凑成target的值在nums中的位置为v。(即nums[i]=k时,nums[v]+num[i]=target。)
边在字典中记下互补这个位置(value)所需互补数(key)边遍历nums数组,之后的遇到nums[i]=之前记录的某个互补数时就是找到了,返回他的位置(value)和 i 就完成了。

相关文章:

  • 2019-10-20
  • 2022-01-18
  • 2021-12-03
  • 2021-05-29
  • 2019-08-06
  • 2020-06-15
  • 2021-08-07
  • 2019-09-22
猜你喜欢
  • 2019-11-10
  • 2018-05-10
  • 2021-09-02
  • 2018-10-27
  • 2022-01-23
  • 2021-11-04
  • 2020-03-02
相关资源
相似解决方案