标签:
题目:
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
C++解答一(传统方法,Runtime: 19 ms):
1 struct Node 2 { 3 int num; 4 int pos; 5 }; 6 7 bool cmp(Node a,Node b) 8 { 9 return a.num<b.num; 10 } 11 12 13 class Solution { 14 public: 15 vector<int> twoSum(vector<int> &numbers, int target) { 16 17 vector<int> result; 18 vector<Node> tmp; 19 Node a; 20 21 for(int i = 0;i<numbers.size();i++) 22 { 23 a.pos = i+1; 24 a.num = numbers[i]; 25 tmp.push_back(a); 26 } 27 28 sort(tmp.begin(),tmp.end(),cmp); 29 int j = tmp.size()-1; 30 int tmpvalue = 0; 31 32 for(int i = 0;i<tmp.size();) 33 { 34 tmpvalue = tmp[i].num+tmp[j].num; 35 if(tmpvalue==target) 36 { 37 if(tmp[i].pos<tmp[j].pos) 38 { 39 result.push_back(tmp[i].pos); 40 result.push_back(tmp[j].pos); 41 } 42 else 43 { 44 result.push_back(tmp[j].pos); 45 result.push_back(tmp[i].pos); 46 } 47 48 break; 49 } 50 else if(tmpvalue>target) 51 { 52 j--; 53 } 54 else 55 { 56 i++; 57 } 58 } 59 60 return result; 61 } 62 };
C++ 解答二(巧妙方法,Runtime: 35 ms):
1 class Solution { 2 public: 3 vector<int> twoSum(vector<int> &numbers, int target) { 4 int i, sum; 5 vector<int> results; 6 map<int, int> hmap; 7 for(i=0; i<numbers.size(); i++){ 8 if(!hmap.count(numbers[i])){ 9 hmap.insert(pair<int, int>(numbers[i], i)); 10 } 11 if(hmap.count(target-numbers[i])){ 12 int n=hmap[target-numbers[i]]; 13 if(n<i){ 14 results.push_back(n+1); 15 results.push_back(i+1); 16 return results; 17 } 18 19 } 20 } 21 return results; 22 } 23 };
标签:
原文地址:http://www.cnblogs.com/zhujudah/p/4464099.html