改不了C的思维
class Solution {
public:
int totalFruit(vector<int>& fruits) {
if(fruits.size() <= 2) return fruits.size();
int left = 0, right = 0, curNum = 0, maxNum = INT_MIN;
int basket[2] = {-1, -1};
while(left <= right && right < fruits.size()){
if(fruits[right] == basket[0] || fruits[right] == basket[1]){
++curNum;
++right;
if(curNum > maxNum) maxNum = curNum;
}else if(basket[0] == -1){
basket[0] = fruits[right++];
++curNum;
if(curNum > maxNum) maxNum = curNum;
}else if(basket[1] == -1){
basket[1] = fruits[right++];
++curNum;
if(curNum > maxNum) maxNum = curNum;
}else{
int tempLeft = right -1;
while(tempLeft > 0 && fruits[tempLeft -1] == fruits[tempLeft]) --tempLeft;
left = tempLeft;
curNum = right - left;
if(basket[0] == fruits[left]){
basket[1] = -1;
}else{
basket[0] = -1;
}
}
}
return maxNum;
}
};
标签:水果,right,maxNum,904,curNum,fruits,basket,tempLeft,成篮 From: https://www.cnblogs.com/llllmz/p/18411134