Posts 「算法刷题」904水果成篮
Post
Cancel

「算法刷题」904水果成篮

参考链接:https://blog.csdn.net/qq_41855420/article/details/92836075

题目链接
904水果成篮904. 水果成篮 - 力扣(LeetCode) (leetcode-cn.com)

构造一个虚拟的窗口[left, right),当窗口tree[left, right)中的水果种数不多于2时,扩大右边界,此时窗口的大小就是可获取的水果种数,否则窗口中的水果种数超过2,则缩小左边界。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution {
public:
    int totalFruit(vector<int>& tree) {
        int treeSize = tree.size(), maxRes = 0;
        int left = 0, right = 0, fruitOne, fruitTwo;//窗口的左、右边界,以及窗口中的两种水果
        while (right < treeSize){
            int tempRes = 1;//窗口的大小
            fruitOne = tree[left++];//第一种水果
            //寻找到第二种水果的第一次出现的位置(并且更新下一次的窗口的left)
            while (left < treeSize && tree[left] == fruitOne){
                ++left;
                tempRes += 1;
            }
            right = left;
            if (right < treeSize){//第二种水果
                fruitTwo = tree[right];
            }
            //当窗口tree[left, right)中的水果种数不多于2时,扩大右边界
            while (right < treeSize){
                if (tree[right] == fruitOne || tree[right] == fruitTwo){
                    ++right;
                    tempRes += 1;
                }
                else {
                    break;
                }
            }
            maxRes = max(maxRes, tempRes);//更新最大的水果数
        }
        return maxRes;
    }

};
This post is licensed under CC BY 4.0 by the author.