题目链接:https://leetcode.cn/problems/fruit-into-baskets/
题意:求最多只包含两种不同元素的最长子串的长度。
思路:双指针,在 right
的左边找到一个最靠左的 left
,使得 [left,right]
子串最多只含有两种不同的数字。
C++ 代码如下:
时间复杂度为 O ( n ) O(n) O(n),空间复杂度为 O ( n ) O(n) O(n)
class Solution {
public:
int totalFruit(vector<int>& fruits) {
int n = fruits.size();
vector<int> cnt(n);
int res = 0;
for (int right = 0, left = 0, type = 0; right < n; right++) {
cnt[fruits[right]]++;
if (cnt[fruits[right]] == 1) type++;
while (type > 2) {
cnt[fruits[left]]--;
if (cnt[fruits[left]] == 0) type--;
left++;
}
res = max(res, right - left + 1);
}
return res;
}
};