滑动窗口练习
题目链接
https://leetcode-cn.com/problems/fruit-into-baskets/
上官方题解代码,自己写了半天90%pass还很复杂,偷看答案。
class Solution {
public int totalFruit(int[] fruits) {
int ans = 0, i = 0;
Counter count = new Counter();
for(int j = 0; j < fruits.length; j++){
//加入count类,计数+1
count.add(fruits[j], 1);
//当count.size >= 3时,从fruits数组最左边开始清,直到fruits.size() == 2
while(count.size() >= 3){
count.add(fruits[i], -1);
if(count.get(fruits[i]) == 0)
count.remove(fruits[i]);
i++;
}
//将满足条件的i,j记录到ans中,保存最大值
ans = Math.max(ans, j - i + 1);
}
return ans;
}
}
class Counter extends HashMap<Integer, Integer>{
public int get(int k){
return containsKey(k)? super.get(k) : 0;
}
public void add(int k ,int v){
put(k, get(k) + v);
}
}
HashMap真是个好东西,super是代指父类(即HashMap类),这题有hashmap用来计数和统计就非常好做,没有就比较麻烦,麻烦就下次再做,告辞。