宝石与石头
题解:
class Solution {
public:
int numJewelsInStones(string jewels, string stones) {
//哈希映射
unordered_map<char,int> hashmap;
//遍历字符串j 加入哈希映射
for(int i = 0;i<jewels.length();i++){
//J中字符不重复 直接加
hashmap[jewels[i]] = 0;
}
//宝石个数
int result = 0;
//遍历s
for(int i = 0;i<stones.length();i++){
if(hashmap.count(stones[i])>0){
//是宝石
result++;
}
}
return result;
}
};
无重复字符的最长子串
题解:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
//无重复字符的字符串 哈希表法
//使用滑动窗口的大小来表示不重复子串的长度
int result = 0;
//使用左指针指向滑动窗口的左边界 便于计算滑动窗口大小
int left = 0;
//字符串的长度
int n = s.length();
if(n == 1){
return 1;
}
//哈希映射 键为字符 值为该字符当前在字符串中出现的最后一次的位置
unordered_map<char,int> hashmap;
//遍历字符串 以i作为滑动窗口的右边界
for(int i=0;i<n;i++){
//如果该字符从未出现 什么也不做 继续遍历即可
//如果该字符出现过 不在滑动窗口内 即hashmap[s[i]]<left 不需要做什么
//在滑动窗口内 更改左边界 该出现字符的下一个字符
//综上
left = max(left,hashmap[s[i]]);
//更新字符出现的最后一次位置 实际上是该字符的下一个位置
hashmap[s[i]] = i+1;
//计算滑动窗口大小
result = max(result,i-left+1);
}
return result;
}
};
四数相加
题解:
class Solution {
public:
int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {
unordered_map<int, int> hashmap;
//key:a+b的数值,value:a+b数值出现的次数
// 遍历A和B,统计两个数组元素之和,和出现的次数,放到map中
for (int a : A) {
for (int b : B) {
hashmap[a + b]++;
}
}
// 统计a+b+c+d = 0 出现的次数
int count = 0;
// 在遍历C和D
for (int c : C) {
for (int d : D) {
if (hashmap.count(0-(c + d))>0) {
//如果 0-(c+d) 在map中出现过 把map中key对应的value也就是出现次数统计出来。
count += hashmap[0 - (c + d)];
}
}
}
return count;
}
};
前K个高频元素
题解:
class Solution {
public:
//哈希映射根据值排序
static bool CmpByValue(const pair<int,int>& lhs, const pair<int,int>& rhs) {
//降序
return lhs.second > rhs.second;
}
vector<int> topKFrequent(vector<int>& nums, int k) {
//理解:出现频率排序 输出前k高
vector<int> result;
//哈希映射 键为数字 值为出现次数
unordered_map<int,int> hashmap;
//遍历数组
for(int i = 0;i<nums.size();i++){
if(hashmap.count(nums[i])>0){
//存在
hashmap[nums[i]]++;
}else{
//不存在
hashmap[nums[i]] = 1;
}
}
//哈希映射 按值排序
vector<pair<int,int>> sortValue(hashmap.begin(),hashmap.end());
sort(sortValue.begin(),sortValue.end(),CmpByValue);
for(int i = 0;i<k;i++){
result.push_back(sortValue[i].first);
}
return result;
}
};