[Leetcode] Two Sum

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

 

先排序,再从两头求解,然后找下标,注意可能有相等的元素。找下标的时候可从分别从前后方向找。

 

 1 class Solution {
 2 public:
 3     vector<int> twoSum(vector<int> &numbers, int target) {
 4         vector<int> v = numbers;
 5         sort(v.begin(), v.end());
 6         int a = 0, b = v.size() - 1;
 7         while (a < b) {
 8             if (v[a] + v[b] > target) {
 9                 b--;
10             } else if (v[a] + v[b] < target) {
11                 a++;
12             } else {
13                 break;
14             }
15         }
16         for (int i = 0; i < v.size(); ++i) {
17             if (v[a] == numbers[i]) {
18                 a = i + 1;
19                 break;
20             }
21         }
22         for (int i = v.size() - 1; i >= 0; --i) {
23             if (v[b] == numbers[i]) {
24                 b = i + 1;
25                 break;
26             }
27         }
28         vector<int> res;
29         res.push_back(a > b ? b : a);
30         res.push_back(a > b ? a : b);
31         return res;
32     }
33 };

 还可以用map、hash_map来做。

 1 class Solution {
 2 public:
 3     vector<int> twoSum(vector<int> &numbers, int target) {
 4         vector<int> res;
 5         map<int, int> mp;
 6         for (int i = 0; i < numbers.size(); ++i) {
 7             if (mp[target-numbers[i]] != 0) {
 8                 int idx1 = mp[target-numbers[i]] > i + 1 ? i + 1 : mp[target-numbers[i]];
 9                 int idx2 = mp[target-numbers[i]] < i + 1 ? i + 1 : mp[target-numbers[i]];
10                 res.push_back(idx1);
11                 res.push_back(idx2);
12                 return res;
13             }
14             mp[numbers[i]] = i + 1;
15         }
16         return res;
17     }
18 };

 

posted @ 2014-03-28 14:38  Eason Liu  阅读(197)  评论(0编辑  收藏  举报