|
| 1 | +/* |
| 2 | + *Given an array of integers, return indices of the two numbers such that they add up to a specific target. |
| 3 | + *You may assume that each input would have exactly one solution. |
| 4 | +
|
| 5 | + *Example: |
| 6 | + *Given nums = [2, 7, 11, 15], target = 9, |
| 7 | + *Because nums[0] + nums[1] = 2 + 7 = 9, |
| 8 | + *return [0, 1]. |
| 9 | +
|
| 10 | + *UPDATE (2016/2/13): |
| 11 | + *The return format had been changed to zero-based indices. Please read the above updated description carefully |
| 12 | +
|
| 13 | + *Tag: Array, Hash Table |
| 14 | + |
| 15 | + *Author: Linsen Wu |
| 16 | +*/ |
| 17 | + |
| 18 | +#include "stdafx.h" |
| 19 | +#include "iostream" |
| 20 | +#include <vector> |
| 21 | +#include <unordered_map> |
| 22 | + |
| 23 | +using namespace std; |
| 24 | + |
| 25 | +class Solution { |
| 26 | +public: |
| 27 | + vector<int> twoSum(vector<int> &numbers, int target) { |
| 28 | + vector<int> indexResults; |
| 29 | + unordered_map<int, int> index_map; |
| 30 | + unordered_map<int, int>::iterator it; |
| 31 | + for (int i=0; i<numbers.size(); ++i) { |
| 32 | + it = index_map.find(target-numbers[i]); |
| 33 | + if (it != index_map.end()) { |
| 34 | + indexResults.push_back(it->second); |
| 35 | + indexResults.push_back(i); |
| 36 | + return indexResults; |
| 37 | + } else { |
| 38 | + index_map[numbers[i]] = i; |
| 39 | + } |
| 40 | + } |
| 41 | + return indexResults; |
| 42 | + } |
| 43 | +}; |
| 44 | + |
| 45 | +/* |
| 46 | +Save the numbers into an unordered map when searching |
| 47 | +Time: O(n) |
| 48 | +Space: O(n) |
| 49 | +*/ |
| 50 | + |
| 51 | +int _tmain(int argc, _TCHAR* argv[]) |
| 52 | +{ |
| 53 | + vector<int> input, output; |
| 54 | + input.push_back(-1); |
| 55 | + input.push_back(7); |
| 56 | + input.push_back(11); |
| 57 | + input.push_back(15); |
| 58 | + |
| 59 | + Solution _solution; |
| 60 | + output = _solution.twoSum(input, 6); |
| 61 | + |
| 62 | + for(vector<int>::iterator iterator = output.begin(); iterator != output.end(); iterator++) |
| 63 | + cout<<((*iterator))<<endl; |
| 64 | + |
| 65 | + system("Pause"); |
| 66 | + |
| 67 | + return 0; |
| 68 | +} |
| 69 | + |
| 70 | + |
| 71 | + |
0 commit comments