leetcode刷题(python)--1. twoSum


两数之和(twoSum)

给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。

你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。

例子:

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

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        dict = {}
        nums_len = len(nums)
        for i in range(nums_len):
            x = nums[i]
            if target - x in dict:
                return [dict[target - x], i] 
            else:
                dict[x] = i 


猜你喜欢

转载自blog.csdn.net/u014180553/article/details/80046209