904. 水果成篮

滑动窗口法

class Solution {
    public int totalFruit(int[] fruits) {

        /**
         * 滑动窗口
         * 最多只能存在两种数字,right从1开始
         * i和j记录最先遇到的两种数字,一旦发现第三种数字,就记录当前的长度
         */
        int left = 0;
        int right = 1;
        int max = 0;
        int i = -1;
        int j = -1;

        while (right <= fruits.length - 1){

            /**
             * i记录第一种数字
             */
            i = fruits[left];

            if (fruits[right] != i){

                /**
                 * j记录第二种数字
                 */
                if (j == -1){
                    j = fruits[right++];
                }
                else if (j != fruits[right]){

                    /**
                     * 如果出现了第三种数字,就让left移动到下一位,重新循环
                     */
                    max = Math.max(max, right - left);
                    left++;
                    right = left + 1;
                    j = -1;
                }
                else {
                    right++;
                }
            }
            else {
                right++;
            }
        }

        /**
         * 有可能所有元素都满足条件,这样max的大小在循环中不会更新,因此需要最后再比较一下
         */
        return Math.max(max, right - left);
    }
}

/**
 * 时间复杂度 O(n)
 * 空间复杂度 O(1)
 */

https://leetcode-cn.com/problems/fruit-into-baskets/

posted @ 2022-02-17 13:46  振袖秋枫问红叶  阅读(30)  评论(0)    收藏  举报