1. 程式人生 > >904. Fruit Into Baskets(python+cpp)

904. Fruit Into Baskets(python+cpp)

題目:

In a row of trees, the i-th tree produces fruit with typetree[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

解釋:
判斷從哪個index開始,有一個連續的子字串,僅僅包含兩種數字而且子字串的總長度最長。
維持一個只有兩個key值的字典,每次遍歷到一個樹都需要更新一下max_len。
python代:

class Solution:
    def totalFruit(self, tree):
        """
        :type tree: List[int]
        :rtype: int
        """
        _dict={}
        start=0
        max_len=0
        for i in range(len(tree)):
            _dict[tree[i]]=_dict.get(tree[i],0)+1
            while len(_dict)>2:
                _dict[tree[start]]-=1
                if _dict.get(tree[start],0)==0:
                    del _dict[tree[start]]
                start+=1
            max_len=max(max_len,i-start+1)
        return max_len       

c++程式碼 :

#include<map>
using namespace std;
class Solution {
public:
    int totalFruit(vector<int>& tree) {
        map<int,int>_map;
        int max_len=0;
        int start=0;
        for(int i=0;i<tree.size();i++)
        {
            _map[tree[i]]+=1;
            while (_map.size()>2)
            {
                _map[tree[start]]-=1;
                if (_map[tree[start]]==0)
                    _map.erase(tree[start]);
                start++;
            }
            max_len=max(max_len,i-start+1);
        }
        return max_len;
    }
};

總結: