Solving methods
1. Violence solving method (time complexity O (n*n)): Iterate through each element first, then traverse the remaining elements to see if the x+y=target is satisfied .
2, we can reduce the time complexity to O (n)by mapping the values to the index using hash.
#include <iostream>#include<windows.h>#include<time.h>#include<vector>#include<unordered_map>using namespacestd;classsolution{ Public: Vector<int>twosum (vector<int> &numbers,inttarget) {Unordered_map<int,int>mapping; Vector<int>result; for(inti =0; I < numbers.size (); i++) {Mapping[numbers[i]]=i; } for(inti =0; I < numbers.size (); i++) { Const intGap = target-Numbers[i]; if(Mapping.find (GAP)!=mapping.end () &&mapping[gap]>i) {result.push_back (i+1); Result.push_back (Mapping[gap]+1); Break; } } returnresult; }};intMain () {solution sum; Vector<int>numbers= {2,7, One, the}; inttarget =9; time_t Clockbegin, Clockend; Clockbegin=clock (); Sum.twosum (numbers, target); Clockend=clock (); //cout << "spend time:" << clockend-clockbegin << Endl;printf"%ld\n", clockend-clockbegin); GetChar (); return 0;}
Note: The return type is a result sorted by index size, used unordered_map for lookup, and the complexity is O (n)
This method is wrong if the data is destroyed by using the current sort, which requires the index of the data to be returned.
If the given data is already sorted, use the dichotomy method to find and then determine the time complexity of O (Nlogn).
Leetcode--twosum