滑動窗口(二)——leetcode No. 904. Fruit Into Baskets(籃子放水果)

題目:

In a row of trees, the i-th tree produces fruit with type tree[i].

You start at any tree of your choice, then repeatedly perform the following steps:

Add one piece of fruit from this tree to your baskets. If you cannot, stop. Move to the next tree to the right of the current tree. If there is no tree to the right, stop. Note that you do not have any choice after the initial choice of starting tree: you must perform step 1, then step 2, then back to step 1, then step 2, and so on until you stop.

You have two baskets, and each basket can carry any quantity of fruit, but you want each basket to only carry one type of fruit each.

What is the total amount of fruit you can collect with this procedure?

Example 1:

Input: [1,2,1] Output: 3 Explanation: We can collect [1,2,1]. Example 2:

Input: [0,1,2,2] Output: 3 Explanation: We can collect [1,2,2]. If we started at the first tree, we would only collect [0, 1]. Example 3:

Input: [1,2,3,2,2] Output: 4 Explanation: We can collect [2,3,2,2]. If we started at the first tree, we would only collect [1, 2]. Example 4:

Input: [3,3,3,1,2,1,1,2,3,3,4] Output: 5 Explanation: We can collect [1,2,1,1,2]. If we started at the first tree or the eighth tree, we would only collect 4 fruits.

Note:

1 <= tree.length <= 40000 0 <= tree[i] < tree.length

思路:

這道題是非常典型的滑動窗口,雖然leetcode把它定義爲medium,但是由於它限制了籃子的數目爲2,所以其實比easy難度高不了多少.

我們首先從第一顆樹開始收果子,然後如果收到的果子種類types>2,那麼說明要拋棄前面的同種類的果子知道types<=2,然後繼續往下收果子就行,可以用一個數組來表示收到的果子種類types

代碼:

class Solution {
    public int totalFruit(int[] tree) {
        int [] arr = new int [40005];
        int types=0;
        int start=0;
        int maxLen=-1;
        for(int i=0;i<tree.length;i++){
            if(arr[tree[i]]==0)
                types++;
            arr[tree[i]]++;
            while(types>2){
                arr[tree[start]]--;
                if(arr[tree[start]]==0)
                    types--;
                start++;
            }
            if(types==2&&maxLen<i-start+1){
                maxLen=i-start+1;
            }
        }
        return (types==1)?tree.length:maxLen;
    }
}

分析:

可知,第一個for循環和while(type>2)是串行的,也就是說不是每個i都會進入while循環,也不是每個i都會在while中循環i-1次,仔細觀察可知雖然有兩個嵌套循環,但其實他們複雜度是並列的,所以最終時間複雜度爲O(n)

這裏只有兩個籃子,而如果籃子數目不定,爲k,那麼這道題的2要改成k,且最後的return部分的==1要改成!=k,詳情可以見滑動窗口系列的(三)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章