Leetcode 1 -- 两数之和 -- Python

@Leetcode 1 – 两数之和 – Python

题目

Leetcode 1 -- 两数之和 -- Python_第1张图片

题目分析

  • 暴力法: 直接进行两次for循环
  • 采用字典: 现把list都存储进字典,在进行一个for循环遍历,找符合要求的值
  • 采用字典模拟哈希表: 边存储进字典,边遍历。

代码

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

字典法

//字典
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]: 
        dict = {}
        for i, j in enumerate(nums):
            dict[j] = i
        for i, j in enumerate(nums):
            temp = target - j
            if dict.get(temp) is not None and dict.get(temp) != i:
                return [i, dict.get(temp)]
        

//字典简化
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        dict = { }
        for i, j in enumerate(nums):
            if dict.get(target-j) is not None:
                return [dict.get(target-j), i]
            dict[j] = i

每天一点进步,加油!。1


  1. @Qichao ↩︎

你可能感兴趣的:(LeetCode)