[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

新建一个数组,分别保存原数组的值和索引,并对新数组按值排序,之后按照2Sum的方法,左右两根指针就可以找解了。O(n)

 1 struct Node
 2 {
 3     int val;
 4     int index;
 5     Node(){}
 6     Node(int v, int idx):val(v), index(idx){}
 7 };
 8 
 9 bool compare(const Node &lhs, const Node &rhs)
10 {
11     return lhs.val < rhs.val;
12 }
13 
14 class Solution {
15 public:
16     vector<int> twoSum(vector<int> &numbers, int target) {
17         // Start typing your C/C++ solution below
18         // DO NOT write int main() function
19         vector<Node> a;
20         for(int i = 0; i < numbers.size(); i++)
21             a.push_back(Node(numbers[i], i + 1));
22         sort(a.begin(), a.end(), compare);
23         
24         int i = 0;
25         int j = numbers.size() - 1;
26         while(i < j)
27         {
28             int sum = a[i].val + a[j].val;
29             if (sum == target)
30             {
31                 vector<int> ret;
32                 int minIndex = min(a[i].index, a[j].index);
33                 int maxIndex = max(a[i].index, a[j].index);
34                 ret.push_back(minIndex);
35                 ret.push_back(maxIndex);
36                 return ret;
37             }
38             else if (sum < target)
39                 i++;
40             else
41                 j--;
42         }
43     }
44 };
posted @ 2012-11-15 21:15  chkkch  阅读(3171)  评论(3编辑  收藏  举报