904. Fruit Into Baskets(python+cpp)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_21275321/article/details/84000137

题目:

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;
    }
};

总结:

猜你喜欢

转载自blog.csdn.net/qq_21275321/article/details/84000137
今日推荐