LeetCode 之 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.

此题为了减少时间,肯定不能用暴力解决的方法,学渣综合了网上好多人的方法,先将学渣的思路说一下:

1假设从0点开始走,设两个index,一个为start,一个为current,start代表此次是从start开始走,current代表从start开始走到了current,如图1

2 设一个int叫做myGas,代表当前我的车所剩的油量,开始为0

3 车当前走在i点,判断能否向前走,此时需要判断myGas+gas[current]-cost[current]是否为非负数,如果可以向前走,立刻走一步,然后把油量更新,然后判断start和current是否相等,如果相等,说明这个点可以走一圈,返回这个坐标;如果不能往前走,说明当前设起始点不行,需要回退一个考虑

4 在起始点回退时,由于起始点也会有油量的消耗和库存,把结余的油量加在当前的油箱里,判断是否能够前行

5如果start==current,说明已经走了一圈,都不行,此时返回-1

综合如图2



图1


                                          图2 

代码(44ms):

class Solution {
public:
    int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        
        int start = 0;
        
        int current = 0;
        
        int myGas = 0;
        
        do{
            //可以继续前进
            if(myGas + gas[current] >= cost[current] ){
                //车上的油更新
                myGas=myGas + gas[current] - cost[current];
                current=(current+1)%gas.size();
                if(current == start){
                    //回到了原点,说明能够循环
                   return current;
                }
            }
            
            else{
                //如果不能前进,起始点向前走一位,而且要把起始点的油加在车里,负数也要加上去
                start= (start+gas.size()-1)%gas.size();
                myGas = myGas + gas[start] - cost[start];
            }
            
         //一圈都不能循环,中断循环   
        }while(start!=current);
        return -1;
    }
   
};

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值