最大滑动窗口
解题思路
while(j<nums.length()){
while [i,j]不符合条件:
i++; //当i符合条件时,立刻退出,保证窗口的最大值
updateResult();
j++;
}
Leetcode904水果成篮
题目描述
想要尽可能多地收集水果。然而,农场的主人设定了一些严格的规矩,你必须按照要求采摘水果:
你只有 两个 篮子,并且每个篮子只能装 单一类型 的水果。每个篮子能够装的水果总量没有限制。
你可以选择任意一棵树开始采摘,你必须从 每棵 树(包括开始采摘的树)上 恰好摘一个水果 。采摘的水果应当符合篮子中的水果类型。每采摘一次,你将会向右移动到下一棵树,并继续采摘。
一旦你走到某棵树前,但水果不符合篮子的水果类型,那么就必须停止采摘。
题解
public int totalFruit(int[] fruits) {
int i = 0;
int j = 0;
HashMap<Integer,Integer> windows = new HashMap<>();
int res = 0;
while(j < fruits.length) {
if(windows.containsKey(fruits[j]) || windows.size() < 2){
res = Math.max(res, j - i + 1);
windows.put(fruits[j], windows.getOrDefault(fruits[j], 0) + 1);
j++;
}else{
res = Math.max(res,j - i);
if (windows.get(fruits[i]) > 1){
windows.put(fruits[i], windows.get(fruits[i])-1);
} else {
windows.remove(fruits[i]);
}
i++;
}
}
return res;
}
最小滑动窗口
解题思路
while(j<nums.length()){
while [i,j] 符合条件:
updateResult();
i++; //尽可能地压缩窗口,保证窗口最小值
j++;
}
Leetcode209长度最小的子数组
题目描述
给定一个含有 n 个正整数的数组和一个正整数 target 。
找出该数组中满足其和 ≥ target 的长度最小的 连续子数组 [numsl, numsl+1, …, numsr-1, numsr] ,并返回其长度。如果不存在符合条件的子数组,返回 0
题解
public int minSubArrayLen(int target, int[] nums) {
int res = Integer.MAX_VALUE;
int j = -1;
int sum = 0;
for (int i = 0;i < nums.length;i++) {
sum += nums[i];
if (sum < target) {
continue;
}
while (sum >= target) {
sum -= nums[++j];
}
res = Math.min(res, i - j + 1 ) ;
}
return res > nums.length ? 0 : res;
}
Leetcode76 最小覆盖子串
题目描述
给你一个字符串 s 、一个字符串 t 。返回 s 中涵盖 t 所有字符的最小子串。如果 s 中不存在涵盖 t 所有字符的子串,则返回空字符串 “” 。
对于 t 中重复字符,我们寻找的子字符串中该字符数量必须不少于 t 中该字符数量。
如果 s 中存在这样的子串,我们保证它是唯一的答案。
题解
public String minWindow(String s, String t) {
//最小
int i = 0;
int j = 0;
Map<Character,Integer> map = new HashMap<>();
int window = 0;
for (char c : t.toCharArray()) {
map.put(c,map.getOrDefault(c,0)+1);
window++;
}
int cnt = 0;
int min = Integer.MAX_VALUE;
String res ="";
Map<Character,Integer> maps = new HashMap<>();
while (j < s.length()) {
if(map.containsKey(s.charAt(j))&&(
!maps.containsKey(s.charAt(j))||map.get(s.charAt(j))>maps.get(s.charAt(j)))){
cnt++;
}
maps.put(s.charAt(j),maps.getOrDefault(s.charAt(j),0)+1);
while(i <= j && window==cnt){
//符合条件,缩小i
res = min < j-i+1?res:s.substring(i,j+1);
min = Math.min(min,j-i+1);
if(maps.containsKey(s.charAt(i))&&map.containsKey(s.charAt(i))&&
map.get(s.charAt(i))>=maps.get(s.charAt(i))){
cnt--;
}
maps.put(s.charAt(i),maps.get(s.charAt(i))-1);
if(maps.get(s.charAt(i))==0){
maps.remove(s.charAt(i));
}
i++;
}
j++;
}
return res;
}