LC.P904[水果成篮]

方法一:滑动窗口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public int totalFruit(int[] fruits) {
int n = fruits.length, ans = 0, total = 0;
int[] cnt = new int[n + 1];
for (int i = 0, j = 0; i < n; ++i) {
if (++cnt[fruits[i]] == 1) ++total;
while (total > 2) {
if (--cnt[fruits[j++]] == 0) --total;
}
ans = Math.max(ans, i - j + 1);
}
return ans;
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(n)$