LeetCode算法笔记-Array组-Two Sum(Python版)

Description:

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.

Translate:

给一组整数,返回两个之和等于给定的特殊目标值的数的索引。
你可以假设每个输入将有一个确切的解决方案,但您不能使用相同元素的两次。

Example:

Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

Solution:

class Solution(object):
    def twoSum(self, nums, target):
        if len(nums) <= 1:
            return False
        buff_dict = {}
        for i in range(len(nums)):
            if nums[i] in buff_dict:
                return [buff_dict[nums[i]], i]
            else:
                buff_dict[target - nums[i]] = i

by:https://leetcode.com/problems/two-sum/discuss/17

Analysis:

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,469评论 0 23
  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,351评论 0 33
  • 也没有拎多重的东西,可是两条胳膊到现在疼得抬不起来。才发觉,除了偶而碰见的,如今,自己身边连帮忙都不知道该找谁。究...
    深夜芝士阅读 1,157评论 0 0
  • 我没有见过会飞的小强, 打不死的蟑螂。 哪怕它的生命是多么顽强, 也逃不过你的脚掌。
    HRH阅读 1,326评论 0 1
  • 1 昨夜,转发王宝强离婚声明到朋友圈,提醒诸位文友,抓住热点,赶紧写文。 睡之前,关于王宝强老婆出轨的事情,各种声...
    梁超文阅读 2,472评论 2 1