码迷,mamicode.com
首页 > 其他好文 > 详细

Two Sum_Leetcode

时间:2018-11-12 11:14:27      阅读:100      评论:0      收藏:0      [点我收藏+]

标签:指针   创建   方法   ber   and   核心   元素   一个   solution   

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


 

Two Sum_Leetcode

标签:指针   创建   方法   ber   and   核心   元素   一个   solution   

原文地址:https://www.cnblogs.com/phinza/p/9944514.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!