【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.

Note:
The solution is guaranteed to be unique.


 

题解:

不管从哪个点开始,能够绕一圈的充要条件是所有的gas[i]之和大于等于所有的cost[i]之和,只要这个条件满足,那么必然存在一个点,从该点出发,可以绕一圈。

剩下的问题就是怎么把这个点找出来,从第一个点开始,试探着往前走,并用一个sum变量统计当前邮箱中剩余的油量,如果在某一个点油量为负了,说明刚才走的路线不可行。那么记录当前点为startPoint,再从这一点重新往前走;如果到某一点油量又为负,那么舍弃刚刚走过的路线,记当前点为startPoint,再重新从当前点开始......直到走到终点的时候,通过判断所有gas[i]之和与cost[i]之和的大小,确定是否能够狗完成遍历。如果不可以,返回-1,否则返回最近一个startPoint(这个startPoint一定可行,因为其他的点都被尝试过并且排除了,而stratPoint一定存在,所以这个startPoint必然可行)。

代码如下:

复制代码
 1 public class Solution {
 2     public int canCompleteCircuit(int[] gas, int[] cost) {
 3         int startPoint = -1;
 4         int currentSum = 0;
 5         int total = 0;
 6         
 7         for(int i = 0;i < gas.length;i++){
 8             total += gas[i] - cost[i];
 9             currentSum += gas[i] - cost[i];
10             if(currentSum < 0)
11             {
12                 currentSum = 0;
13                 startPoint = i;
14             }
15         }
16         
17         return total >= 0 ? startPoint+1:-1;
18     }
19 }
复制代码
posted @   SunshineAtNoon  阅读(188)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示