|
| 1 | +//Author: Linsen Wu |
| 2 | + |
| 3 | +#include "stdafx.h" |
| 4 | +#include "iostream" |
| 5 | +#include <vector> |
| 6 | +#include <unordered_map> |
| 7 | + |
| 8 | +using namespace std; |
| 9 | + |
| 10 | +class Solution { |
| 11 | +public: |
| 12 | + vector<int> twoSum(vector<int> &numbers, int target) { |
| 13 | + vector<int> indexResults; |
| 14 | + unordered_map<int, int> index_map; |
| 15 | + unordered_map<int, int>::iterator it; |
| 16 | + for (int i=0; i<numbers.size(); ++i) { |
| 17 | + it = index_map.find(target-numbers[i]); |
| 18 | + if (it != index_map.end()) { |
| 19 | + indexResults.push_back(it->second); |
| 20 | + indexResults.push_back(i+1); |
| 21 | + return indexResults; |
| 22 | + } else { |
| 23 | + index_map[numbers[i]] = i+1; |
| 24 | + } |
| 25 | + } |
| 26 | + return indexResults; |
| 27 | + } |
| 28 | +}; |
| 29 | + |
| 30 | +/* |
| 31 | +class Solution { |
| 32 | +public: |
| 33 | + vector<int> twoSum(vector<int> &numbers, int target) { |
| 34 | + vector<int> indexResults; |
| 35 | + for(vector<int>::iterator iterator1 = numbers.begin(); iterator1 != numbers.end(); iterator1++) |
| 36 | + { |
| 37 | + for(vector<int>::iterator iterator2 = iterator1+1; iterator2 != numbers.end(); iterator2++) |
| 38 | + { |
| 39 | + if((*iterator1 + *iterator2) == target) |
| 40 | + { |
| 41 | + int index1 = iterator1 - numbers.begin() + 1; |
| 42 | + int index2 = iterator2 - numbers.begin() + 1; |
| 43 | + indexResults.push_back(index1); |
| 44 | + indexResults.push_back(index2); |
| 45 | + } |
| 46 | + } |
| 47 | + } |
| 48 | + return indexResults; |
| 49 | + } |
| 50 | +};*/ |
| 51 | + |
| 52 | +int _tmain(int argc, _TCHAR* argv[]) |
| 53 | +{ |
| 54 | + vector<int> input, output; |
| 55 | + input.push_back(-1); |
| 56 | + input.push_back(7); |
| 57 | + input.push_back(11); |
| 58 | + input.push_back(15); |
| 59 | + |
| 60 | + Solution _solution; |
| 61 | + output = _solution.twoSum(input, 6); |
| 62 | + |
| 63 | + for(vector<int>::iterator iterator = output.begin(); iterator != output.end(); iterator++) |
| 64 | + cout<<((*iterator))<<endl; |
| 65 | + |
| 66 | + system("Pause"); |
| 67 | + |
| 68 | + return 0; |
| 69 | +} |
| 70 | + |
| 71 | + |
| 72 | + |
0 commit comments