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

1. Two Sum

时间:2018-07-07 22:14:55      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:type   https   iss   利用   ict   put   遍历   runtime   inpu   

1. Two Sum

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.
Example: Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].

问题描述

虑一个整数列表,返回两个数字的索引,使得这两个整数之和等于给定的目标值。假定每个输入有唯一解,且每个元素不能重复使用。
举例:给定列表 nums = [2,7,11,15], 目标 target = 9, 返回 [0,1].

问题分析

  • 最容易想到也最粗暴的解法,就是对每一个值,都遍历一遍列表,遇到另一个求和为目标值的数,就输出这两个数的索引,这样的话,时间复杂度为\(O(n^2)\),空间复杂度为\(O(1)\)。要降低时间复杂度,就要想到利用空间复杂度。这里声明一个字典用来建立两个整数和目标值之间的关系。
  • 字典的键用来存储当前数字需要的那个数字,键值用来存储当前数字的索引。这样,在遍历列表的过程中,对每个遇到的数字,判断该数字是否在字典里。如果在,就找到了这个数字,可以输出其索引,同时字典的键值表示另一个数字的索引,即找到了答案。如果不在,则存储键、键值对,键为目标值减去当前值,键值为当前值的索引。此时,时间复杂度为\(O(n)\),空间复杂度为\(O(n)\).
    以举例具体来说:
nums = [2,7,11,15]
target = 9
- 开始
- 定义空字典 hash_dict = {}
-- 遍历列表nums
-- 遍历到第一个数2,检查是否在hash_dict中;发现不在
-- 则,存储target-2(目标值与当前值的差),0(当前值的索引)到字典中;此时hash_dict = {7:0}
-- 遍历到第二个数7,检查是否在hash_dict中;发现在
-- 则,输出[hash_dict[7],1],即[0,1]
- 结束
  • 这种方式的关键在于应用字典,将每次遍历的整数所需要的另一个数记录下来,同时也记录下当前整数的索引,在之后的遍历中,一旦找到这个整数,即可得到需要的两个索引,省去了两层循环的嵌套搜索。

    代码

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

测试结果

  • Runtime:36 ms
  • beats 100% of python3 submissions
    技术分享图片

1. Two Sum

标签:type   https   iss   利用   ict   put   遍历   runtime   inpu   

原文地址:https://www.cnblogs.com/initial-h/p/9278205.html

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