Topic:
Given an array of integers, find the numbers such that they add up to a specific target number.
The function twosum should return indices of the numbers such that they add up to the target, where index1 must is Les S than Index2. Please note that your returned answers (both Index1 and INDEX2) is not zero-based.
You may assume this each input would has exactly one solution.
Input:numbers={2, 7, one, A, target=9
Output:index1=1, index2=2
C + + Solution one (traditional method, runtime:19 ms):
1 structNode2 {3 intnum;4 intPos;5 };6 7 BOOLCMP (Node a,node B)8 {9 returna.num<B.num;Ten } One A - classSolution { - Public: thevector<int> Twosum (vector<int> &numbers,inttarget) { - -vector<int>result; -Vector<node>tmp; + Node A; - + for(inti =0; I<numbers.size (); i++) A { atA.pos = i+1; -A.num =Numbers[i]; - Tmp.push_back (a); - } - - sort (Tmp.begin (), Tmp.end (), CMP); in intj = tmp.size ()-1; - intTmpvalue =0; to + for(inti =0;i<tmp.size ();) - { theTmpvalue = tmp[i].num+Tmp[j].num; * if(tmpvalue==target) $ {Panax Notoginseng if(tmp[i].pos<Tmp[j].pos) - { the Result.push_back (tmp[i].pos); + Result.push_back (tmp[j].pos); A } the Else + { - Result.push_back (tmp[j].pos); $ Result.push_back (tmp[i].pos); $ } - - Break; the } - Else if(tmpvalue>target)Wuyi { thej--; - } Wu Else - { Abouti++; $ } - } - - returnresult; A } +};
C + + Solution II (ingenious method, runtime:35 ms):
1 classSolution {2 Public:3vector<int> Twosum (vector<int> &numbers,inttarget) {4 inti, sum;5vector<int>results;6map<int,int>Hmap;7 for(i=0; I<numbers.size (); i++){8 if(!Hmap.count (Numbers[i])) {9Hmap.insert (pair<int,int>(Numbers[i], i));Ten } One if(Hmap.count (target-Numbers[i])) { A intn=hmap[target-Numbers[i]]; - if(n<i) { -Results.push_back (n+1); theResults.push_back (i+1); - returnresults; - } - + } - } + returnresults; A } at};
The Twosum of Leetcode