Leetcode 134. 加油站

原题链接:Leetcode 134. 加油站

在这里插入图片描述
在这里插入图片描述
我屎一样的代码。。。面向测试样例的编程

class Solution {
public:
    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
        int start = -1;
        int n = cost.size();
        vector<int> tonext(n);
        int all = 0, cnt0 = 0;
        for (int i = 0; i < n; i++) {
            tonext[i] = gas[i] - cost[i];
            all += tonext[i];
            if (tonext[i] == 0)
                cnt0++;
        }
        if (all < 0)
            return start;
        if (cnt0 == n)
            return 0;
        vector<int> left(n);
        vector<int> right(n);
        for (int i = 1; i < n; i++) {
            left[i] = left[i - 1] + tonext[i - 1];
        }
        right[n - 1] = tonext[n - 1];
        for (int i = n - 2; i >= 0; i--) {
            right[i] = right[i + 1] + tonext[i];
        }
        for (int i = 0; i < n; i++) {
            if (tonext[i] <= 0 || right[i] < 0)
                continue;
            int tmp = 0;
            for (int j = i; j < n; j++) {
                if (tmp < 0)
                    break;
                tmp += tonext[j];
            }
            if (tmp >= 0)
                return i;
        }
        return start;
    }
};

官方题解思路: 如果从x出发最多能到y,那么x到中间的所有位置(假设有cnt个),最多也只能到y,那么就忽略从这些地方出发的可能,下一次的出发点本来应该是x+1,现在直接为x+1+cnt

class Solution {
public:
    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
        int n = cost.size();
        int i = 0;
        while (i < n) {
            int cnt = 0;
            int sumgas = 0;
            int sumcost = 0;
            int now = i;
            while (cnt < n) {
                sumgas += gas[now];
                sumcost += cost[now];
                if (sumgas < sumcost)
                    break;
                cnt++;
                now = (now + 1) % n;
            }
            if (cnt == n)
                return i;
            else
                i = i + cnt + 1;
        }
        return -1;
    }
};

  • 8
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值