用哈希表(unordered_map)使得时间复杂度从O(n*n)降到O(n),空间复杂度从O(1)增到O(n);一边找一边插入哈希表
注意
在C++11以前要使用unordered_map需要
#include<tr1/unordered_map>//在unordered_map之前加上tr1库名,
using namespace std::tr1;//与此同时需要加上命名空间
class twoSum { public: vector<int> f1(vector<int>& nums, int target) { unordered_map<int, int> hash; vector<int> result; for (int i = 0; i < nums.size(); i++) { int numToFind = target - nums[i]; if (hash.find(numToFind) != hash.end()) { result.push_back(hash[numToFind]); result.push_back(i); return result; } hash[nums[i]] = i; } return result; } };
原文:http://www.cnblogs.com/lzd233/p/6254628.html