LeetCode1-Two Sum In Python

本题题目是给一个target,通过给定的target找到列表里面和为该值的两数,并返回它们的下标。

解题:考虑使用字典,通过遍历列表,看字典里面是否有与当前值和为target的值存在,若有,则返回两个下标,若没有,则把当前数字加入到字典。需要注意的是字典里key为当前数字,value为下标。

代码:

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        dic=dict()
        for i in range(len(nums)):
            if (target-nums[i]) in dic:
                return [dic[target-nums[i]],i]
            else:
                dic[nums[i]]=i
        return []

猜你喜欢

转载自blog.csdn.net/nlxxqqh1/article/details/88095113