LeetCode OJ: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.

加油站问题,每个加油站可以加的油给出来,从当前当下一个加油站会消耗的汽油量给出来了,求从哪个站点出发可以循环加油站一圈。

一开始是用一个二重循环的,这样复杂度为N^2,一直TLE,代码如下:

 1 class Solution {
 2 public:
 3     int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
 4         for(int i = 0; i < gas.size(); ++i){
 5             int j = i;
 6             int curGas = gas[j];
 7             while(curGas >= cost[j]){
 8                 curGas -= cost[j];
 9                 j = (j+1)%gas.size();
10                 curGas += gas[j];
11                 if(j == i)
12                     return i;
13             }
14         }
15         return -1;
16     }
17 };

 那只能使用其他方法了,可以看出维护一个部分差的和,如果前面的部分差的和一旦小于0的话,那么可以肯定的是应该在当前节点的下一处开始,然后在维护一个整体的和,当检查部分和可以完成时,查看整体差值是否小于0就可以了,代码如下所示:

 1 class Solution {
 2 public:
 3     int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
 4         int totalLeft = 0;
 5         int sum = 0;
 6         int j = -1;
 7         for(int i = 0; i < gas.size(); ++i){
 8             totalLeft += gas[i] - cost[i];
 9             sum += gas[i] - cost[i];
10             if(sum < 0){
11                 j = i;
12                 sum = 0;
13             }
14         }
15         if(totalLeft < 0)
16             return -1;
17         return j + 1;
18     }
19 };

 

转载于:https://www.cnblogs.com/-wang-cheng/p/5000557.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值