Original title Link: https://oj.leetcode.com/problems/two-sum/
Despite the violence, the problem has two well-known practices:
1. Sort first, then one last double pointer. It is important to note that the original index must be saved in order to be sorted based on the value of the struct with value and index.
2. Direct Hash. The question to note is that if the array has two identical elements, it still poses a unique solution. For example, Target is 6 and the array is 1,3,3. So the hash key is int, but value is a vector<int> that holds all of the index. Many blogs on the web assume that each value in the array is unique and may be tested, but not the solid solution.
Class Solution {public:vector<int> Twosum (vector<int> &numbers, int target) {vector<int> Results Unordered_map<int, vector<int> > map; for (int i = 0; i < numbers.size (); ++i) {if (Map.find (numbers[i]) = = Map.end ()) {Map.inser T (Make_pair (Numbers[i], vector<int> (1, i))); } else {map[numbers[i]].push_back (i); }} for (int i = 0; i < numbers.size (); ++i) {int searched = Target-numbers[i]; if (map.find (searched)! = Map.end ()) {if (searched! = Numbers[i]) { Results.push_back (i + 1); Results.push_back (Map[searched][0] + 1); Break } else if (map[searched].size () = = 1) {continue; } else {Results.push_back (map[searched][0] + 1); Results.puSh_back (Map[searched][1] + 1); Break }}} sort (Results.begin (), Results.end ()); return results; }};
[Leetcode] 1-two Sum