力扣第374场周赛
找出峰值
模拟
class Solution {
public:
vector<int> findPeaks(vector<int>& mountain) {
vector<int>ans;
for(int i = 1 ; i < mountain.size() - 1; i ++){
if(mountain[i] > mountain[i-1] && mountain[i] > mountain[i+1]){
ans.push_back(i);
}
}
return ans;
}
};
需要添加的硬币的最小数量
贪心遍历,假设现在得到了0~(s-1)内的所有整数,如果此时新发现了一个整数 x,那么把x加到已得到的数字中,就得到了x~(s+x−1)内的所有整数。
class Solution {
public:
int minimumAddedCoins(vector<int>& coins, int target) {
sort(coins.begin() , coins.end());
//当前0~cur的值都可以得到
sort(coins.begin(), coins.end());
long long ans = 0 , cur = 0 , n = coins.size();
for (int x : coins) {
while (x > cur + 1) {
cur += cur + 1;
ans++;
}
cur += x;
}
while (cur < target) {
cur += cur + 1;
ans++;
}
return ans;
}
};
统计完全子字符串
条件二分段,条件一滑窗统计
class Solution {
int f(string s, int k) {
int res = 0;
for (int m = 1; m <= 26 && k * m <= s.length(); m++) {
int cnt[26]{};
auto check = [&]() {
for (int i = 0; i < 26; i++) {
if (cnt[i] && cnt[i] != k) {
return;
}
}
res++;
};
for (int right = 0; right < s.length(); right++) {
// 滑窗记录个数
cnt[s[right] - 'a']++;
int left = right + 1 - k * m;
if (left >= 0) {
check();//是否满足条件一
cnt[s[left] - 'a']--;
}
}
}
return res;
}
public:
int countCompleteSubstrings(string word, int k) {
int n = word.length();
int ans = 0;
for (int i = 0; i < n;) {
int st = i;
//分段
for (i++; i < n && abs(int(word[i]) - int(word[i - 1])) <= 2; i++);
ans += f(word.substr(st, i - st), k);
}
return ans;
}
};
–