标签:
Solution 1:
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { unordered_map<int, int> myMap; vector<int> result; for(size_t i = 0; i < nums.size(); ++i) { myMap[nums[i]] = i; } for(size_t i = 0; i < nums.size(); ++i) { const int gap = target - nums[i]; auto it = myMap.find(gap); if(it != myMap.end() && it->second != i) { result.push_back(i); result.push_back(myMap[gap]); break; // Assume that each input would have
// exactly one solution } } return result; } };
Solution 2: 暴力查找,超时
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> result; for(size_t i = 0; i < nums.size(); ++i) { for(size_t j = i + 1; j < nums.size(); ++j) { if(nums[i] + nums[j] == target) { result.push_back(i); result.push_back(j); break; } } } return result; } };
Solution 3:
标签:
原文地址:http://www.cnblogs.com/xuyan505/p/5335210.html