leetcode1-两数之和

思路:

1.使用暴力,两遍循环数组;

2.使用哈希表(字典),一遍循环即可。将数作为key,对应的索引作为value。注意a[b]!=i条件的限制

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        a={}
        for i ,j in enumerate(nums):
            a[j]=i
        
        for i,j in enumerate(nums):
            b=target-j
            if b in a and a[b]!=i:
                return [i,a[b]]

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-04-07
  • 2021-12-05
  • 2021-05-19
  • 2021-04-20
猜你喜欢
  • 2021-12-03
  • 2021-11-07
  • 2021-10-29
  • 2022-12-23
  • 2021-07-06
  • 2021-09-14
相关资源
相似解决方案