1vector<int> Twosum (vector<int> &numbers,inttarget)2 {3 //Key is the number and value are its index in the vector.4unordered_map<int,int>Hash; Unordered_map is an unordered associative container5vector<int>result;6 for(inti =0; I < numbers.size (); i++) {7 intNumbertofind = target-Numbers[i];8 9 //if Numbertofind is found in map, return themTen if(Hash.find (numbertofind)! =Hash.end ()) {//find () returns an iterator that points to the first element of value in the interval [first,last] (hash ordinal), and returns the last if not found One //+1 because indices is not zero based AResult.push_back (Hash[numbertofind] +1);//push_back (t) Insert T in front of A.end () -Result.push_back (i +1); - returnresult; the } - - //Number is not found. Put it in the map. -Hash[numbers[i]] =i; + } - returnresult; +}
Unordered associative containers are: unordered_set unordered_multiset unordered_map unordered_multimap, which use keys and hash tables so that data can be accessed quickly. Without the Lower_bound and upper_bound of the ordered associative containers, the comparison is based on the concept of equals.
Twosum (c + +)