904. Fruit Into Baskets

传送门

问题分析

本问题重点在优化从何处再次搜索tree,这里我使用lastLoc用于记录不同类型最后一次出现的位置下标。那么我们再次搜索时只用从min(lastLoc[0], lastLoc[1]) + 1 出发就可以了,这样可以从一定程度上加速搜索速度。

源码

class Solution {
public:
    int totalFruit(vector<int>& tree) {
        int sum{0}, amount{0}, typeLoc = {0}, loc;
        int type[2] = {-1, -1};
        int lastLoc[2] = {-1, -1};
        for(int i = 0; i < tree.size(); i++){
            if(typeLoc < 2){
                if(typeLoc == 1 && type[0] == tree[i]){
                    lastLoc[typeLoc] = i;
                }
                else{
                    type[typeLoc] = tree[i];
                    lastLoc[typeLoc] = i;
                    typeLoc++;
                }
                sum++;
            }
            else{
                // type in basket
                if(type[0] == tree[i] || type[1] == tree[i]) {
                    if(type[0] == tree[i])  lastLoc[0] = i;
                    if(type[1] == tree[i])  lastLoc[1] = i;
                    sum++;
                }
                // type not in basket
                else {
                    i = min(lastLoc[0], lastLoc[1]);
                    for(int i = 0; i < 2; i++){
                        type[i] = -1;
                        lastLoc[i] = -1;
                    }
                    amount = max(sum, amount);
                    typeLoc = 0;
                    sum = 0;
                }
            }
        }
        return max(amount, sum);            
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值