leetcode 134. Gas Station

水深无声 2022-06-08 11:24 267阅读 0赞

1、题目

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],从加油站i到i+1的耗油为cost[i]。汽车的油箱容量不限。求从哪个站点出发可以跑完全程,不存在则返回-1。

Note:
The solution is guaranteed to be unique.

2、分析

gas[i]-cost[i]等于从i到i+1还剩的油量。
int current 记录当前剩油量
int total 记录总剩油量
从0站点开始遍历:
对每站gas[i]-cost[i]求和。current+=gas[i]-cost[i],total+=gas[i]-cost[i]
如果累计剩油量current<0,则0-i的所有站点都不可能作为出发点。(因为跑不到下一站就没油了)。把i+1设置为新出发点,current重置。

遍历结束后:如果total<0,说明总体是跑不到的,返回-1;否则返回找到的起始点。

3、代码

  1. int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
  2. int total = 0;//总剩油量
  3. int current = 0;//当前剩油量
  4. int start = 0;
  5. for (int i = 0; i < gas.size(); i++) {
  6. current += gas[i] - cost[i];
  7. total += gas[i] - cost[i];
  8. if (current < 0)//i和之前的所有站点不能成为起始点
  9. {
  10. start = i + 1;
  11. current = 0;
  12. }
  13. }
  14. return total < 0 ? -1 : start;
  15. }

发表评论

表情:
评论列表 (有 0 条评论,267人围观)

还没有评论,来说两句吧...

相关阅读