双指针法
双指针法可以看成是虫在蠕动,先右指针移动,然后左指针在根据判定条件,不断移动,直至满足判定条件。接着右指针再次移动,如此循环
用代码模板可以看成
int left = 0;
int right = 0;
int res = 0;
while(right < nums.size()){
sum+=nums[right];
while(不满足条件时){
sum-=nums[left];
left--;
}
res = max(res, right - left + 1);
right++;
}
return res;
例题
class Solution {
public int characterReplacement(String s, int k) {
char[] cs = s.toCharArray();
int[] cnt = new int[26];
int ans = 0;
for (int l = 0, r = 0; r < s.length(); r++) {
// cnt[cs[r] - 'A']++;
int cur = cs[r] - 'A';
cnt[cur]++;
// while (!check(cnt, k)) cnt[cs[l++] - 'A']--;
while (!check(cnt, k)) {
int del = cs[l] - 'A';
cnt[del]--;
l++;
}
ans = Math.max(ans, r - l + 1);
}
return ans;
}
boolean check(int[] cnt, int k) {
int max = 0, sum = 0;
for (int i = 0; i < 26; i++) {
max = Math.max(max, cnt[i]);
sum += cnt[i];
}
return sum - max <= k;
}
}
class Solution {
public:
int equalSubstring(string s, string t, int maxCost) {
int sum = 0;
vector<int> diff;
for(int i = 0; i < s.size(); i++){
diff.push_back(abs(s[i] - t[i]));
}
int left = 0;
int right = 0;
int maxlength = 0;
while(right < diff.size()){
sum += diff[right];
while(sum > maxCost){
sum-=diff[left];
left++;
}
maxlength = max(maxlength, right - left + 1);
right++;
}
return maxlength;
}
};
滑动窗口
滑动窗口可以看成特殊的双指针,只不过右指针和左指针的距离保持定值
class Solution {
public:
double findMaxAverage(vector<int>& nums, int k) {
double maxsum = 0;
double cursum = 0;
for(int i = 0; i < k; i++){
cursum+= nums[i];
}
maxsum = cursum;
for(int i = k; i < nums.size(); i++){
cursum = cursum - nums[i-k] + nums[i];
maxsum = max(maxsum, cursum);
}
return maxsum/k;
}
};