LeetCode-1- Two Sum
来源:互联网 发布:软件可行性方案模板 编辑:程序博客网 时间:2024/06/06 05:17
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:
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:
class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ dictMap = {} for index, value in enumerate(nums): if target - value in dictMap: return [dictMap[target - value] , index ] dictMap[value] = index
博客园博客:欠扁的小篮子
1 0
- LeetCode 1 - Two Sum
- leetcode 1 Two Sum
- Leetcode【1】:Two Sum
- [leetcode 1] Two Sum
- 【leetcode-1】Two Sum
- [leetcode 1] Two Sum
- [Leetcode] 1 - Two Sum
- LeetCode (1) Two Sum
- LeetCode 1:《Two Sum》
- LeetCode | #1 Two Sum
- leetcode-1 Two Sum
- Two Sum | LeetCode(1)
- [Leetcode]1Two Sum
- leetcode 1 Two Sum
- leetcode #1 Two Sum
- leetcode 1:Two Sum
- LeetCode 1 Two Sum
- leetcode #1 two sum
- Android系统透明栏(Translucent Bars)使用SystemBarTint的实现攻略
- View和ViewGroup的区别以及自定义控件步骤小结
- 【hdoj_1009】FatMouse's Trade
- 分析http应用层
- 时钟同步问题
- LeetCode-1- Two Sum
- 九度OJ 1009 二叉搜索树
- MFC线程的全面总结
- PHP的socket详解
- windows文件操作函数
- 8 固若金汤:网站的安全架构
- 模板类中的友元函数使用注意
- Leetcode 284. Peeking Iterator
- Ubuntu下Hive配置(MySQL数据库的安装方式)