目录
题型总结
1. 两数之和
解析
题解
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
// 60.专题十_哈希表_两数之和_C++
unordered_map<int, int> hash;
for(int i = 0; i < nums.size(); ++i)
{
int x = target - nums[i];
if(hash.count(x)) return {i, hash[x]};
hash[nums[i]] = i;
}
return {-1, -1};
}
};
面试题 01.02. 判定是否互为字符重排
解析
题解
class Solution {
public:
bool CheckPermutation(string s1, string s2) {
// 61.专题十_哈希表_判定是否互为字符重排_C++
if(s1.size() != s2.size()) return false;
int hash[26] = {0};
for(auto ch1 : s1)
hash[ch1 - 'a']++;
for(auto ch2 : s2)
{
hash[ch2 - 'a']--;
if(hash[ch2 - 'a'] < 0) return false;
}
return true;
}
};
217. 存在重复元素
解析
题解
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
// 62.专题十_哈希表_存在重复元素I_C++
unordered_set<int> hash;
for(auto x : nums)
{
if(hash.count(x)) return true;
else hash.insert(x);
}
return false;
}
};
219. 存在重复元素 II
解析
题解
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
// 63.专题十_哈希表_存在重复元素II_C++
unordered_map<int, int> hash;
int n = nums.size();
for(int i = 0; i < n; ++i)
{
if(hash.count(nums[i]) && abs(hash[nums[i]] - i) <= k) return true;
else hash[nums[i]] = i;
}
return false;
}
};
49. 字母异位词分组
解析
题解
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
// 64.专题十_哈希表_字母异位词分组_C++
unordered_map<string, vector<string>> hash;
// 1.把所有的字母异位词分组
for(auto& s : strs)
{
string tmp = s;
sort(tmp.begin(), tmp.end());
hash[tmp].push_back(s);
}
// 2.结果提取出来
vector<vector<string>> ans;
for(auto& [x, y] : hash)
{
ans.push_back(y);
}
return ans;
}
};