☘前言☘
开更五月集训专题,由浅入深,深入浅出,飞向大厂!
🧑🏻作者简介:一个从工业设计改行学嵌入式的年轻人
✨联系方式:2201891280(QQ)
⏳全文大约阅读时间: 20min
全文目录
1984. 学生分数的最小差值
解题思路1
排序之后直接计算就好了。
代码
class Solution {
public:
int minimumDifference(vector<int>& nums, int k) {
sort(nums.begin(),nums.end());
int n = nums.size(),ans = 100000;
for(int i = 0;i <= n - k;++i)
ans = min(ans,nums[i + k - 1] - nums[i]);
return ans;
}
};
注意的点
- ans要初始为最大值哦。
1876. 长度为三且各字符不同的子字符串
解题思路1
典型滑动窗口应用
代码
class Solution {
public:
int countGoodSubstrings(string s) {
int hash[26] = {0},hashsome = 0,n = s.size(),ans = 0;
if(n < 3) return ans;
for(int i = 0;i < 3;++i){
if(hash[s[i] - 'a'] == 1 ) ++hashsome;
++hash[s[i] - 'a'];
}
if(!hashsome) ++ans;
for(int i = 3;i < n;++i){
if(--hash[s[i - 3] - 'a'] == 1) --hashsome;
if(hash[s[i] - 'a'] == 1) ++hashsome;
++hash[s[i] - 'a'];
if(!hashsome) ++ans;
}
return ans;
}
};
注意的点
注意是hash值为1的时候才会增加相同次数。
1839. 所有元音按顺序排布的最长子字符串
解题思路
直接用map进行映射之后直接进行hash表记录就好了。
代码
class Solution {
public:
int longestBeautifulSubstring(string word) {
char tmp[] = "aeiou";
map<char,int> Maps;
int hash[5] = {0},ans = 0,n = word.size(),left = 0;
for(int i = 0;i < 5;++i) Maps[tmp[i]] = i;
++hash[Maps[word[0]]];
for(int i = 1;i < n;++i){
if(Maps[word[i]] < Maps[word[i - 1]]){
bool flag = true;
for(int j = 0;j < 5;++j){
if(!hash[j]) flag = false;
hash[j] = 0;
}
if(flag) ans = max(ans,i - left);
left = i;
++hash[Maps[word[i]]];
}
else ++hash[Maps[word[i]]];
}
bool flag = true;
for(int j = 0;j < 5;++j){
if(!hash[j]) flag = false;
hash[j] = 0;
}
if(flag) ans = max(ans,n - left);
return ans;
}
};
注意的点
复杂度好像有点高0.0
1052. 爱生气的书店老板
解题思路
也是水题。
代码
class Solution {
public:
int maxSatisfied(vector<int>& customers, vector<int>& grumpy, int minutes) {
char yuanyin[] = "aeiou";
map<char,int> Maps;
for(int i = 0;i < 5;++i) Maps[yuanyin[i]] = i;
int ans = 0,tmpans = 0, n = customers.size();
for(int i = 0;i < n;++i) //统计一开始就不生气的人
if(!grumpy[i])
ans += customers[i],customers[i] = 0;//原地hash 哈哈哈哈
for(int i = 0;i < n && i < minutes;++i)
tmpans += customers[i];
int ansmax = tmpans;
for(int i = minutes;i < n;++i){
tmpans -= customers[i - minutes];
tmpans += customers[i];
ansmax = max(ansmax, tmpans);
}
return ans + ansmax;
}
};
注意的点
- 这个题目给我扯
进入商店的顾客的编号
,其实应该是人数。老坑人了。
写在最后
最近还是沉迷水墨屏,回头做完一定要b站视频。c站文章,太折磨了,呜呜呜。