[Leetcode] Two Sum
2014-03-28 14:38
113 查看
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
先排序,再从两头求解,然后找下标,注意可能有相等的元素。找下标的时候可从分别从前后方向找。
还可以用map、hash_map来做。
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> v = numbers; sort(v.begin(), v.end()); int a = 0, b = v.size() - 1; while (a < b) { if (v[a] + v[b] > target) { b--; } else if (v[a] + v[b] < target) { a++; } else { break; } } for (int i = 0; i < v.size(); ++i) { if (v[a] == numbers[i]) { a = i + 1; break; } } for (int i = v.size() - 1; i >= 0; --i) { if (v[b] == numbers[i]) { b = i + 1; break; } } vector<int> res; res.push_back(a > b ? b : a); res.push_back(a > b ? a : b); return res; } };
还可以用map、hash_map来做。
class Solution { public: vector<int> twoSum(vector<int> &numbers, int target) { vector<int> res; map<int, int> mp; for (int i = 0; i < numbers.size(); ++i) { if (mp[target-numbers[i]] != 0) { int idx1 = mp[target-numbers[i]] > i + 1 ? i + 1 : mp[target-numbers[i]]; int idx2 = mp[target-numbers[i]] < i + 1 ? i + 1 : mp[target-numbers[i]]; res.push_back(idx1); res.push_back(idx2); return res; } mp[numbers[i]] = i + 1; } return res; } };
相关文章推荐
- leetcode第一刷_Two sum
- [LeetCode]Two Sum
- Two Sum (LeetCode)
- LeetCode Two Sum
- LeetCode(1) Two Sum
- LeetCode - Two Sum
- LeetCode | 初入LeetCode,一刷Two Sum
- two sum - leetcode
- LeetCode - 1. Two Sum
- leetcode-1-Two Sum
- Leetcode 1 two sum 难度:0
- LeetCode-Two Sum
- LeetCode -- Two Sum
- [LeetCode]:Two Sum
- 第一周:[LeetCode]1. Two Sum
- [leetcode]51 Two Sum
- LeetCode:Two Sum
- leetcode 1 Two Sum
- LeetCode 1 Two Sum
- Leetcode: Two Sum