加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

leetcode No134. Gas Station

发布时间:2020-12-13 21:19:28 所属栏目:PHP教程 来源:网络整理
导读:Question 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 th

Question

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个汽油站,i站的汽油有gas[i]汽油。现在有1辆无穷容量油箱的车,它从i站开到(i+1)需要耗费cost[i]汽油。如果这辆车可以走完这个圈,那末返回这个车的出发点,否者返回⑴.

Algorithm

  • 如果从A到不了B,那末A-B之间的任何1站都到不了B(B是从A开始第1个不能到达的站)
  • 如果各个站的油量总和超过需要消耗油量总和,则1定有解

Accepted Code

class Solution {
public:
    int canCompleteCircuit(vector<int>& gas,vector<int>& cost) {
        int start=0,tank=0,total=0;
        for(int i=0;i<gas.size();i++)
        {
            tank+=gas[i]-cost[i];
            if(tank<0)
            {
                total+=tank;
                tank=0;
                start=i+1;
            }
        }
        return ((total+tank)<0)?-1:start;
    }
};

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读