Leetcode Two Sum

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_31390999/article/details/80720216
这道题一看就是使用dict解决,如果字典中有,返回信息,如果没有,将遍历的值放到字典中
class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        dict = {}  #字典可以存键和值两个最适合
        for i in range(len(nums)):
            if target - nums[i] in dict:
                return [dict[target-nums[i]],i]
            dict[nums[i]] = i  
        return []
        

猜你喜欢

转载自blog.csdn.net/qq_31390999/article/details/80720216