leetcode Gas Station

本文介绍了一个简单的算法,用于解决汽车能否在加满油的情况下完成一圈行驶的问题。通过判断是否存在一个起点,使得汽车从该点出发并沿环路行驶时始终有足够的油继续前进,最终返回该起点。若无法找到这样的起点,则返回-1。

此题思路较为简单,即判断是否存在从某一点开始,在保证每经过一个加油站都加上所有油的前提下,汽车都保持行驶状态,直至行驶完一圈。

需要注意的是程序结束条件。

代码

class Solution {
public:
    int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
        
        int start = 0;
        int j = start;
        int gasAll = gas[j];
        int size = gas.size();
        int count = 0;
     
        while(true)
        {
            if(count==size)
                return start;
            else
            {
                if(gasAll>=cost[j])
                  {
                      gasAll -= cost[j];
                      j = (j+1)%size;
                      gasAll += gas[j];
                      count++;
                  }
                  else
                  {
                      start = (start+1)%size;
                      if(start==0)
                          return -1;
                      j = start;
                      gasAll = gas[j];
                      count = 0;
                  }
            }
            
        }
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值