力扣hot100——哈希
1. 两数之和
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> ans;
map<int, int> mp;
for (int i = 0; i < nums.size(); i++) {
if (mp.count(target - nums[i])) {
ans.push_back(mp[target - nums[i]]);
ans.push_back(i);
return ans;
}
mp[nums[i]] = i;
}
return ans;
}
};
模拟
49. 字母异位词分组
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>> res;
if(strs.empty())
{
return res;
}
unordered_map<string,vector<string>> mp;
for(auto str:strs)
{
string key=str;
sort(key.begin(),key.end());
mp[key].emplace_back(str);
}
for(auto it=mp.begin();it!=mp.end();it++)
{
res.emplace_back(it->second);
}
return res;
}
};
模拟
128. 最长连续序列
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_map<int, int> ump;
for (auto x: nums) {
ump[x]++;
}
int ans = 0;
for (auto it = ump.begin(); it != ump.end(); it++) {
int x = it->first;
if (ump.count(x - 1)) continue;
int t = x;
int s = 0;
while (ump.count(t)) {
s++;
t++;
}
ans = max(ans, s);
}
return ans;
}
};
哈希,贪心
每次遇到只需要从一个连续序列的最开始的数查找即可