leetcode 1 Two Sum
2015-12-14 23:37
387 查看
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
#include <iostream>
#include <stdio>
#include <vector>
#include <map>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> ans;
map<int, int> num2exit;
for(int i = 0; i < nums.length(); i++) {
map[nums[i]] = i;
}
int another = 0, i1 = 0, i2 = 0;
for (int i = 0; i < nums.length(); ++i)
{
another = target - nums[i];
if(num2exit.count(another)) {
i2 = num2exit[another];
if(i2 != i1) break;
}
}
ans.push_back(i1+1);
ans.push_back(i2+1);
return ans;
}
}
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
#include <iostream>
#include <stdio>
#include <vector>
#include <map>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> ans;
map<int, int> num2exit;
for(int i = 0; i < nums.length(); i++) {
map[nums[i]] = i;
}
int another = 0, i1 = 0, i2 = 0;
for (int i = 0; i < nums.length(); ++i)
{
another = target - nums[i];
if(num2exit.count(another)) {
i2 = num2exit[another];
if(i2 != i1) break;
}
}
ans.push_back(i1+1);
ans.push_back(i2+1);
return ans;
}
}
相关文章推荐
- 数据结构-Java实现-链表回顾
- OpenCV3.0丢失Nonfree模块
- Java开发者必备的六款工具
- Essential Notes on Database(III) Normalization 范式 (I)
- 有吧友需要PDF的下载站点,好吧,我这边汇总一下
- Oracle 汉字在不同字符集下所占字节
- Github上如何取消fork别人的repository
- Android多媒体应用——通知的使用(Notification)
- oc中自定义结构体
- leetcodeMove Zeroes
- Github上如何取消fork别人的repository
- 每天一个linux命令--more/less
- 【随笔】聊一聊服务器的那些事儿
- 图像编程-彩色图像灰度化
- 微软公布2015年度Bing最热搜索榜单
- 微软公布2015年度Bing最热搜索榜单
- 蓝桥杯 算法训练 集合运算
- Mina是什么
- Redhat6.6 图形化安装 oracle12c
- 解决django关于图片无法显示的问题