博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Leetcode] Gas Station 加油站
阅读量:7038 次
发布时间:2019-06-28

本文共 1240 字,大约阅读时间需要 4 分钟。

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.

贪心法

复杂度

时间 O(N) 空间 O(K)

思路

我们把将gas中每个值都减去cost中对应的值,这样gas就成为了开出该加油站到下一个加油站时,该加油站加的油用剩到多少。这样我们用一个tank变量记录汽车每开到一个加油站后油箱里累计剩下多少油,每到一个加油站就更新。这样我们开始遍历gas数组,如果tank是负数,说明开出该加油站后无法到达下一个加油站,这样旅程的起点更新为下一个加油站。因为旅程是环状的我们遍历的加油站数组应为2*gas.length-1,这样能保证我们以最后一个加油站为起点时也能继续验证。

代码

public class Solution {    public int canCompleteCircuit(int[] gas, int[] cost) {        // gas减去cost,得到净油值        for(int i = 0; i < cost.length; i++){            gas[i] -= cost[i];        }        int tank = 0, res = -1;        for(int i = 0; i < gas.length * 2 - 1; i++){            int idx = i % gas.length;            // 更新油箱            tank += gas[idx];            // 如果油箱为负,说明走不到下一个加油站            if(tank < 0){                res = idx + 1;                tank = 0;            }        }        // 如果起点在最后一个加油站之后,说明无解        return res >= gas.length ? -1 : res;    }}

转载地址:http://puial.baihongyu.com/

你可能感兴趣的文章
《Adobe Illustrator CC经典教程》—第0课0.8节创建和编辑渐变
查看>>
《Dreamweaver CS6完美网页制作——基础、实例与技巧从入门到精通》——第2章 网页色彩知识2.1 网页配色基础...
查看>>
物联网设备安全1.6 小结
查看>>
细数二十世纪最伟大的十大算法
查看>>
《机器学习与数据科学(基于R的统计学习方法)》——2.10 SQL数据库
查看>>
MySQL 中你应该使用什么数据类型表示时间?
查看>>
《Visual Basic 2012入门经典》----1.6 设计界面
查看>>
如何在 CentOS/RHEL 中为 Apache Tomcat 绑定 IPv4 地址
查看>>
《21天学通C语言(第7版)》一6.2 控制程序的执行
查看>>
《网页美工设计Photoshop+Flash+Dreamweaver从入门到精通》——2.5 创建文字
查看>>
《易学C++(第2版)》——1.3 选好一种语言
查看>>
Java8中CAS的增强
查看>>
基本线程同步(四)在同步代码中使用条件
查看>>
高管必备思维:区分2类问题和4类可视化方法
查看>>
《C++ 黑客编程揭秘与防范(第2版)》——第6章 加密与解密
查看>>
《Visual C++ 开发从入门到精通》——2.4 输入/输出基础
查看>>
地平线谭洪贺:AI芯片怎么降功耗?从ISSCC2017说起
查看>>
《树莓派用户指南(第3版)》——第1篇 主板 第1章 初识树莓派 1.1 主板简介...
查看>>
MySQL · myrocks · fast data load
查看>>
使用 Linux/Unix 进行文本处理
查看>>