134. Gas Station-贪心算法
来源:互联网 发布:神漫画软件下载 编辑:程序博客网 时间:2024/05/01 02:35
原题链接:134. Gas Station
16 / 16 test cases passed. Runtime: 1 ms Your runtime beats 7.59% of javasubmissions.
【思路2】
【思路1】
从末站开始,startStation和endStation均指向最后一站,一旦发现剩余的油量小于0,那么startStation前移——回去“加油”,直到油量大于等于0,那么endStation开始后移——继续前进。如果最后的剩余油量大于等于0,那么表示可以环游一周,startStation即为解。否则,不可以,返回 -1。
public class Solution { public int canCompleteCircuit(int[] gas, int[] cost) { int start = gas.length - 1, location = 0; int remain = gas[start] - cost[start]; //起点假设为数组的最后一个位置 while(location < start) { //当 location>=start 时,说明已考察完一圈了,不再继续 if (remain < 0) remain += gas[--start] - cost[start]; //油量不足,原先的 start 不适合作为起点,起点前移 else remain += gas[location] - cost[location++]; //油量充足,这个 start 可能是适合的起点,继续前进 } return remain >= 0 ? start : -1; //如果油量大于等于0,那么说明已经成功游历完一圈 }}
16 / 16 test cases passed. Runtime: 1 ms Your runtime beats 7.59% of javasubmissions.
【思路2】
假设startStation = 0,往后开,假设在第 i 站第一次总油量小于0,那么表示 0 至第 i - 1 站均不适合作为起始站,此时总剩余油量 remain1 < 0。那么将第 i 站作为起始站,同样的,一旦发现油量 remain2 < 0,那么就重设起始站。最后遍历完gas之后,如果 totalRemain >= 0,那么startStation就是起始站,并且[startStation, gas.length - 1]必然remain均大于0:
public int canCompleteCircuit(int[] gas, int[] cost) { int startStation = 0, totalRemain = 0, remain = 0; for (int i = 0; i < gas.length; i++) { totalRemain += gas[i] - cost[i]; if (remain < 0) { remain = gas[i] - cost[i]; startStation = i; } else { remain += gas[i] - cost[i]; } } return totalRemain >= 0 ? startStation : -1; }欢迎优化!
1 0
- 134. Gas Station-贪心算法
- leetcode贪心算法:Gas Station
- 134. Gas Station 类别:贪心算法 难度:medium
- [leetcode][贪心] Gas Station
- leetcode---gas-station---贪心
- leetCode #134 Gas Station 贪心
- [LeetCode]134.Gas Station
- LeetCode 134. Gas Station
- [Leetcode] 134. Gas Station
- 134. Gas Station
- [leetcode] 134. Gas Station
- Leetcode-134.Gas Station
- 134. Gas Station LeetCode
- 134. Gas Station
- Leetcode 134. Gas Station
- 134. Gas Station
- 134. Gas Station
- [LeetCode]134. Gas Station
- linux部署mongodb及基本操作
- RatingBar 的使用 以及自定义的RatingBar
- vi 编辑器 命令模式 编辑模式
- LeetCode 231. Power of Two
- 单片机与RS-232的串口通信+VB程序
- 134. Gas Station-贪心算法
- 安装Ubuntu12.04以及sources.list更新源推荐
- 欢迎使用CSDN-markdown编辑器
- C++内存管理
- 骚鸟、骚七能不能超神
- Redis、Memcached简单封装
- 双向链表(非循环)排序
- 虚拟机怎么安装vmware tools
- 卷积神经网络(CNN)就是这么简单