leetcode--17. 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.

沿环形路线有N个加油站,其中第 i 站的煤气量为gas[ i ]。你有一辆有一个无限制油箱的汽车,从 i 站到下一站(i+1)要花费大量的汽油。你从一个加油站并且初始油箱为空开始旅程。如果你可以绕环路一次,返回启程加油站的索引,否则返回-1。
注意:解决方案保证是唯一的。

思路:
用最后一个点作为起点,当油量够时则end++,当油量不够就start后退一个直至到0,换起点后不需计算后续点,只需要计算刚才结余即可

public class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int start = gas.length - 1;
        int end = 0;
        int sum = gas[start] - cost[start];
        while(start > end){
            if(sum > 0){
                sum += gas[end] - cost[end];
                end++;
            } else {
                start--;
                sum += gas[start] - cost[start];
            }
        }
        return sum >= 0 ? start : -1;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,956评论 0 10
  • 第一个VR应用 之前我们已经将Oculus的开发包导入到空工程中了,现在我们来构建第一个桌面VR的示例。开发包中已...
    小太阳会发光诺阅读 326评论 0 0
  • 奥登爷爷家的四个孩子又来到了“神秘农场”,他们在那里还遇到了老朋友迈克。迈克的爸爸死了,他和哥哥妈妈来到了...
    JacobTang阅读 376评论 0 0
  • 我想有个能量补给站 赐予我力量 我想有个时光穿梭机 赐予我岁月与时光 我想有个金刚不坏身 赐予我无限的光阴与力量 ...
    大爱无痕阅读 143评论 0 1

友情链接更多精彩内容