【LeetCode刷题之旅】001 Two Sum【Python】

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_38371360/article/details/86483407

拖了好久,终于开始刷LeetCode了,记录一下我的爬坑之旅。 

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

 此题利用Python中的字典记录下每个元素出现的位置,也就是C++解法中的Hash Map。

class Solution:
    def twoSum(self,nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """

        dictionary = {}                 #创建一个空字典
        for index in range(len(nums)):
            another_nums = target - nums[index]
            if nums[index] in dictionary:    #判断字典d中是否存在nums[index]
                return [dictionary[nums[index]],index]    #返回 [0,1]
            else:
                dictionary[another_nums] = index        
                #如果没有,那么存入字典中,key = another_nums ; value = index

#验证答案
if __name__ == '__main__':
    num = [2, 7, 11, 15]
    target = 9
    solution = Solution()
    print(solution.twoSum(num,target))

步骤:

  1. 建立一个空的字典,用来存储每个元素出来的位置。
  2. 遍历nums中的每一个元素,得到target与其的差值,第一轮 index = 0; target = 9; nums[0] = 2; another_nums = 7
  3. 判断此刻的元素 2 是否在字典中,第一轮发现不在
  4. 如果不在则将其存入到字典中;key = another_nums = 7 ; value = index = 0
  5. 第二轮开始,此时 index = 1; target = 9; nums[0] = 7; another_nums = 2
  6. 判断此刻的元素 7 是否在字典中,第二轮发现在的
  7. 返回一个list,里面是两个index,[0,1]

猜你喜欢

转载自blog.csdn.net/weixin_38371360/article/details/86483407