• 题目描述:求出数组中等于目标值的两个数的索引,假定肯定存在两个数并且同一个索引上的数不能用两次。

  • 思路:

  1. 用空间换时间,使用一个字典存储已经遍历的数字的索引,如果新遍历的数字和target的差值在字典中,则就是结果。
class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        dicts = {}
        for k, v in enumerate(nums):
            if target - v in dicts:
                return [dicts.get(target-v), k]
            dicts[v] = k   

相关文章:

  • 2021-06-08
  • 2021-08-06
  • 2021-08-16
  • 2021-09-14
  • 2022-02-08
  • 2021-06-02
  • 2021-11-28
  • 2021-11-02
猜你喜欢
  • 2021-04-25
  • 2021-10-05
  • 2021-10-23
  • 2021-11-14
  • 2021-09-15
  • 2021-12-24
  • 2021-05-16
相关资源
相似解决方案