题解 | #两数之和#
两数之和
http://www.nowcoder.com/practice/20ef0972485e41019e39543e8e895b7f
暴力解题法&哈希表法
class Solution { public: /** * * @param numbers int整型vector * @param target int整型 * @return int整型vector */ //暴力解题法 vector<int> TraverseSum(vector<int>& numbers, int target){ vector<int> res; for(int i=0; i<=numbers.size()-2; i++){ for(int j=i+1; j<=numbers.size()-1; j++){ if (numbers[i] + numbers[j] == target){ res.push_back(i+1); res.push_back(j+1); } } } return res; } //哈希函数解题法 vector<int> hashSum(vector<int>& numbers, int target){ vector<int> res; unordered_map<int, int> hash; //key:值, value:下标 for(int i=0; i<numbers.size(); i++){ int j = target-numbers[i]; if(hash[j]){ //已经存了两个加数中的另一个 res.push_back(hash[j]); res.push_back(i+1); break; }else{ hash[numbers[i]] = i+1; } } return res; } vector<int> twoSum(vector<int>& numbers, int target){ vector<int> res; // 暴力解题法: res = TraverseSum(numbers, target); res = hashSum(numbers, target); return res; } };