Two Sum_Leetcode

1. Two Sum

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].

这题要求返回的是Index且nums并不是sort好的,诸如双指针等方法便无法很好的使用

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        dic = {} #1.创建一个空字典
        for i in range(len(nums)):
            if nums[i] in dic: #3.如果,当前值在dic(的keys里)里出现过,(找到2里所说的x了!)则其与记录的index对应的元素 合正好为target
                return [dic[nums[i]], i]
            else: #2.解题核心:将当前元素与目标相减,得出的差值以key的形式记录进字典里,其val为当前的index(解释为,需要与x相加才能合为target)
                dic[target - nums[i]] = i


猜你喜欢

转载自www.cnblogs.com/phinza/p/9944514.html