题解之前:
1.有关unordered_map的count功能:查询key!
Leetcode 1.两数之和
解题思路:
class Solution {
public:vector<int> twoSum(vector<int>& nums, int target) {vector<int> res;// key:具体的数值(便于count查看是否存在) value:具体的下标索引idx(ans)unordered_map<int, int> s; for(int i = 0; i < nums.size(); i ++){int left = target - nums[i];if(s.count(left)){ // 已经存在了res.push_back(i); res.push_back(s[left]);break;}s[nums[i]] = i;}return res;}
};
Leetcode 454.四数相加 II
解题思路:
代码:
class Solution {
public:int fourSumCount(vector<int>& nums1, vector<int>& nums2, vector<int>& nums3, vector<int>& nums4) {int res = 0;unordered_map<int, int> s;for(auto a: nums1)for(auto b: nums2)s[a + b] ++;for(auto c: nums3)for(auto d: nums4)res += s[-c - d]; return res;}
};
Leetcode 49.字母异位词分组
算法核心:选择什么作为哈希表的key?
解法一:排序+hash
class Solution {
public:vector<vector<string>> groupAnagrams(vector<string>& strs) {vector<vector<string>> ans;unordered_map<string, int> s;int idx = -1;for(auto v: strs){string cp = v;sort(v.begin(), v.end());if(!s.count(v)){vector<string> t = {cp};ans.push_back(t);s[v] = ++ idx;}else{ans[s[v]].push_back(cp);}}return ans;}
};
解法二:计数+hash
class Solution {
public:vector<vector<string>> groupAnagrams(vector<string>& strs) {int idx = -1;vector<vector<string>> ans;unordered_map<string, int> map;for(auto v: strs){vector<int> cnt(26, 0); // 计数数组// 初始化计数数组for(char c: v)cnt[c - 'a'] ++;// 生成字符串keystring key = "";for(int i = 0; i < 26; i ++){key += 'a' + i;key += cnt[i];}// 看看是否出现过if(!map.count(key)){ // 没有出现过vector<string> t = {v};ans.push_back(t);map[key] = ++ idx;}else // 出现过ans[map[key]].push_back(v);}return ans;}
};