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
Subscribe to see which companies asked this question
Show tagsshow Similar Problems This topic is to pay attention to the conversion of subscript and value
#include <iostream>#include<vector>using namespacestd;classIndexdata { Public: Indexdata () {}intindex; intvalue;};/** 1. Generate a vector and sort the value of the vector * 2. Two pointers, left, right, left < right * 3. If vector[left][1] + vector[right][1] > value, right--; * 4. If vector[left][1] + vector[right][1] < value, left--; * 5. If = =, return, note the size of the return index **/classSolution { Public: Vector<int> Twosum (vector<int>& Nums,inttarget) {Vector<IndexData*>V_data; Vector<int>Res; size_t num_size=nums.size (); size_t I=0; for(; i<num_size; i++) {Indexdata* d =NewIndexdata (); D->index =i; D->value =Nums[i]; V_data.push_back (d); } sort (V_data.begin (), V_data.end (), CMP); intleft =0; intright = Num_size-1; while(Left <Right ) { while(Left < right) && ((V_data[left]->value + v_data[right]->value) >target)) { Right--; } while(Left < right) && ((V_data[left]->value + V_data[right]->value) <target)) { Left++; } if((V_data[left]->value + v_data[right]->value) = =target) { if(V_data[left]->index < v_data[right]->index) {res.push_back (V_data[left]->index +1); Res.push_back (V_data[right]->index +1); } Else{res.push_back (V_data[right]->index +1); Res.push_back (V_data[left]->index +1); } Break; } } for(i=0; i<num_size; i++) { if(NULL! =V_data[i]) { DeleteV_data[i]; V_data[i]=NULL; } } returnRes; }Private: Static BOOLcmpConstindexdata* ID1,Constindexdata*Id2) { returnId1->value < id2->value; }};intmain () {vector<int>v; V.push_back (3); V.push_back (2); V.push_back (4); Solution S; S.twosum (V,6); return 0;}
The Sum of