leetcode刷题系列C++-Gas Station

There are N gas stations along a circular route, where the amount of gas at station i is gas[i].

You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.

Return the starting gas station's index if you can travel around the circuit once, otherwise return -1.

Note:
The solution is guaranteed to be unique.

Subscribe to see which companies asked this question

class Solution {
public:
    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
        const int length = gas.size();
        int sum = 0;
        int total = 0;
        int j = -1;
        for(int i = 0; i < length; ++i)
        {
            sum += gas[i] - cost[i];
            total += gas[i] - cost[i];
            if(sum < 0)
            {
                j = i ;
                sum = 0;
            }
        }
        if(total < 0)
        {
            return -1;
        }
        else
        {
            return j + 1;
        }
    }
};
题目详解:

1.total值是用来记录整个能量圈的正负,如果整个圈都是负值,那么怎么跑都不可能跑完

2.sum值是用来记录里面局部的能量正负,局部可能会gas特别多可以用于下一段,也可能缺失,直接跳到下一个点进行。

总之,只要能量圈的总值是正的,那么就肯定能跑完有解。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值