leetcode 刷题之路 68 Gas Station
来源:互联网 发布:淘宝上卖零食怎么样 编辑:程序博客网 时间:2024/06/16 18:25
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.
一种做法是以每个站为起点判断是否能够在行走一个周期后回到自身。
AC code:
class Solution { public: int canCompleteCircuit(vector<int> &gas, vector<int> &cost) { int res = 0, i = res, n = gas.size(), left = 0; while (res<n) { left = left + gas[i] - cost[i]; if (left<0) { res++; left = 0; i = res; } else { i = (++i) % n; if (i == res) return res; } } return -1; } };其实还有更优化的方法,在判断以当前站点res为起始站点是否能够回到当前站点的过程中,如果在站点i出现不能到达i+1站点的情况,那么以从当前站点res到A直接的所有站点为起始点,都不能跨越过i~i+1这个坎。可以这样理解这句话,对于res~i之间的任意站点x,汽车从res出发到达x剩余的油量大于等于0,所以汽车从res出发到达i剩余的油量大于等于从站点x出发到达i剩余的油量。
基于上面的结论,可以知道,下一个可能的起始点就是i+1,我们直接让res等于i+1,再继续执行程序,直到res等于n,此时说明不存在满足条件的站点。
优化后的方法时间复杂度O(n)。
AC code:
class Solution { public: int canCompleteCircuit(vector<int> &gas, vector<int> &cost) { int res = 0, i = res, n = gas.size(), left = 0; while (res<n) { left = left + gas[i] - cost[i]; if (left<0) { if(i>res) res=i;else res++; left = 0; i = res; } else { i = (++i) % n; if (i == res) return res; } } return -1; } };
0 0
- leetcode 刷题之路 68 Gas Station
- LeetCode 之 Gas Station
- LeetCode之Gas Station
- leetcode之Gas Station
- leetcode之Gas Station
- leetcode之Gas Station
- LeetCode之Gas Station
- Leetcode之Gas Station
- leetcode之Gas Station
- [leetcode刷题系列]Gas Station
- LeetCode刷题笔录Gas Station
- 开始刷题leetcode day5: Gas Station
- leetcode刷题系列C++-Gas Station
- leetCode解题报告之Gas Station
- LeetCode之Gas Station --环形加油站周游
- LeetCode OJ 之 Gas Station (加油站)
- LeetCode:Gas Station
- [LeetCode] Gas Station
- 【cocos2d-x + Lua(1) 绑定Lua并使用tolua++】
- C 语言中常用 string 函数简介
- UVA - 846 Steps
- 安装Tomcat
- wtl在rc中修改控件文本中文显示?乱码的问题
- leetcode 刷题之路 68 Gas Station
- C语言中常用文件读写命令总结
- EasyARM i.mx287学习笔记——minicom配置和使用
- NSUserDefaults的简单使用
- Unity3D脚本:边缘高光脚本
- c++11新性能测试4
- 设计模式之迭代器模式
- JAVA模式之复合模式(composite)思考与应用
- 黑马程序员-异常