Leetcode116: Two Sum
2015-10-24 13:29
274 查看
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
用unorderedmap比map快,一个是hash散列实现,一个是红黑树。
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> res(2); int n = nums.size(); map<int,int> mp; for(int i = 0; i < n; i++) { if(mp.find(target-nums[i]) == mp.end()) mp[nums[i]] = i; else { res[0] = mp[target-nums[i]]+1; res[1] = i+1; } } return res; } };
用unorderedmap比map快,一个是hash散列实现,一个是红黑树。
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> res(2); unordered_map<int, int> mp; for (int i = 0; i < nums.size(); ++i) { /* code */ if(mp.find(target-nums[i]) == mp.end()) mp[nums[i]] = i; else{ res[0] = mp[target-nums[i]]; res[1] = i; break; } } return res; } };python代码:
class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ mp={} for x in range(len(nums)): if target-nums[x] in mp: return [mp[target-nums[x]], x] mp[nums[x]] = x
相关文章推荐
- Android编码规范02
- 图像处理 腐蚀 膨胀 细化
- MyEclipse快捷键大全
- 课后作业加密
- Android网络框架Volley(实战篇)
- 最小生成树
- Joomla - Error-Based SQL Injection
- HDU 1180 诡异楼梯
- 前端Javascript书籍分享
- linux中文手册
- 20135231 —— 第六周任务总结报告
- 第八周 项目二-建立链串算法库
- 读《大道至简》第四章有感
- 简单工厂模式
- MongoDB 学习笔记三 JAVA调用MongoDB
- Hibernate-映射关系- 基于主键映射的1<->1映射
- struts.valueStack (Action 中属性存放的原理)
- 如何在苹果官网下载旧版本的Xcode
- C语言:一组数据中只有一个数字出现了一次。其他所有数字都是成对出现的。请找出这个数字。(
- UVa-10006 Carmichael Numbers