LeetCode 题解(46): Gas Station

题目:

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

You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from stationi 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.

题解:

这里如果用笨办法嵌套两轮循环,计算以每一个station为起点的结果,会超时无法通过。

优化方法是:如果以i为起点,经过i+1,i+2,....一直到点k的结果为负值,即点i无法作为起点完成任务,则i+1,i+2,...k-1,以这些个点为起点都不可能完成任务。因为[i,i+1],[i+1,i+2],...[k-2,k-1]这些个区间gas-cost的值必为正值(如果不为正,则在到k之前就失败了,也就是根本到不了k),而[k-1,k] gas-cost的值必为负,而加上[i,i+1],[i+1,i+2],...[k-2,k-1]这些个区间的正值都无法到达k,那么去掉其中任何一个区间所带来的正值的contribution,就更加无法到达k,所以从i+1到k-1的所有点都不需要作为起点计算了,由此可以直接跳到以k为起点进行计算。


C++版

<pre name="code" class="cpp">int j = 0
class Solution {public: int canCompleteCircuit(vector<int> &gas, vector<int> &cost) { if(!gas.size() || !cost.size()) return -1; for(int i = 0; i < gas.size(); i++) { int current = gas[i]; int pass = 0;
            int j = 0
for(; j < gas.size(); j++) { if(current < cost[(i+j) % gas.size()]) { break; } current = current - cost[(i+j) % gas.size()] + gas[(i+j+1) % gas.size()]; pass++; } if(j == gas.size()) return i; i += pass; } return -1; }};
 



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值