LeetCode -- Two Sum
2014-09-21 23:52
281 查看
从数组中找出两个数之和等于指定值的坐标:
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> m;
for(int i = 0; i < numbers.size(); i++){
if(m.count(numbers[i]) == 0) {
m[target - numbers[i]] = i + 1;
} else {
res.push_back(m[numbers[i]]);
res.push_back(i + 1);
break;
}
}
if(!res.empty()) sort(res.begin(), res.end());
return res;
}
};
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> m;
for(int i = 0; i < numbers.size(); i++){
if(m.count(numbers[i]) == 0) {
m[target - numbers[i]] = i + 1;
} else {
res.push_back(m[numbers[i]]);
res.push_back(i + 1);
break;
}
}
if(!res.empty()) sort(res.begin(), res.end());
return res;
}
};
相关文章推荐
- [Leetcode] Two Sum
- 【LeetCode】Two Sum
- LeetCode 001 Two Sum
- LeetCode 1 - Two Sum
- [leetcode] two sum
- leetcode 1 Two Sum
- LeetCode-1.Two Sum
- LeetCode 1. Two Sum
- LeetCode Practice_1 Two Sum
- leetcode - Two Sum
- LeetCode-1- Two Sum
- 【Leetcode】1. Two Sum
- LeetCode 1. Two sum
- leetcode Two Sum 每日一题 (。・∀・)ノ゙嗨
- Two Sum--leetcode
- Leetcode-Two Sum
- LeetCode之1—-Two Sum
- 【Leetcode】【Medium】Two Sum
- leetcode----Two Sum
- leetcode001:Two Sum