前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode-1- Two Sum

LeetCode-1- Two Sum

作者头像
欠扁的小篮子
发布2018-04-11 11:25:49
4510
发布2018-04-11 11:25:49
举报
文章被收录于专栏:技术碎碎念技术碎碎念

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.

Example:

代码语言:javascript
复制
Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

简言之,查找给定数组内两个数,使得两数和为给定的target

思路:

  遍历给定数组,用一个哈希表存放已经遍历过的值,key是nums中的值,value是其位置索引。

  对于当前遍历的nums[i],查找哈希表中是否存在target-nums[i],若存在,则返回二者索引,否则将(key=nums[i],value=i)放入哈希表中,继续遍历

时间复杂度:O(n)

python代码如下,已AC:

代码语言:javascript
复制
 1 class Solution(object):
 2     def twoSum(self, nums, target):
 3         """
 4         :type nums: List[int]
 5         :type target: int
 6         :rtype: List[int]
 7         """
 8         dictMap = {}
 9         for index, value in enumerate(nums):
10             if target - value in dictMap:
11                 return [dictMap[target - value] , index ]
12             dictMap[value] = index

提交结果:

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016-06-22 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档