LeetCode 1.Two Sum

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

 

Solution

 1 #include<vector>
 2 using namespace std;
 3 class Solution {
 4 public:
 5    vector<int> twoSum(vector<int> &numbers, int target) {
 6         vector<int> copyNumbers=numbers;
 7         sort(copyNumbers.begin(), copyNumbers.end());
 8         
 9         vector<int> result;
10         int minIndex=0;
11         int maxIndex=numbers.size()-1;
12         int sum;
13         while(minIndex<=maxIndex)
14         {
15             sum=copyNumbers[minIndex]+copyNumbers[maxIndex];
16             if(sum==target)
17             {
18                 vector<int>::iterator minIte=find(numbers.begin(),
                   numbers.end(),copyNumbers[minIndex]);
19 vector<int>::reverse_iterator maxIte=find(numbers.rbegin(),
                        numbers.rend(),copyNumbers[maxIndex]);
20 21 result.push_back(&*minIte-&numbers[0]+1); 22 result.push_back(&*maxIte-&numbers[0]+1); 23 break; 24 } 25 else if(sum>target) 26 { 27 maxIndex--; 28 } 29 else 30 minIndex++; 31 } 32 sort(result.begin(),result.end()); 33 return result; 34 } 35 };

 

posted on 2014-12-28 18:35  kyokuhuang  阅读(102)  评论(0编辑  收藏  举报

导航