LeetCode-Two Sum
2014-03-22 02:13
344 查看
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
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
vector<int> res;
map<int, int> hMap;
for(int i=0; i<numbers.size(); i++)
hMap[numbers[i]]=i;
for(int j=0; j<numbers.size(); j++){
int a = target - numbers[j];
if(hMap.find(a) != hMap.end() && j != hMap[a]){
res.push_back(j+1);
res.push_back(hMap[a] + 1);
return res;
}
}
}
};
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> &numbers, int target) {
vector<int> res;
map<int, int> hMap;
for(int i=0; i<numbers.size(); i++)
hMap[numbers[i]]=i;
for(int j=0; j<numbers.size(); j++){
int a = target - numbers[j];
if(hMap.find(a) != hMap.end() && j != hMap[a]){
res.push_back(j+1);
res.push_back(hMap[a] + 1);
return res;
}
}
}
};
相关文章推荐
- LeetCode------Two Sum
- [leetcode, python] Two Sum 两数之和等于某数
- leetcode(1)_Two Sum
- 【Leetcode】Two Sum
- leetcode:Two Sum
- [leetcode] Two Sum
- LeetCode 1 Two Sum 题解
- leetcode--1--two sum
- Leetcode习题: Two Sum
- leetcode001——Two Sum
- [Leetcode]Two Sum
- 【Leetcode】Two Sum
- 【LeetCode-数组篇】 1 Two Sum
- leetcode 46: Two Sum
- LeetCode - Two Sum
- Leetcode- 1. Two Sum
- LeetCode on the way, two sum
- leetcode 1. Two Sum
- leetcode 1-Two Sum
- [Leetcode] Two Sum