leetcode Gas Station
来源:互联网 发布:mac epub mobi 转换 编辑:程序博客网 时间:2024/04/30 04:20
题目链接
目前中等难度的题已经有点算法知识了。不再是单纯的数据结构问题了。
这个问题一看就是贪心算法的。因为。路径无限油箱,加油站这类问题贪心算法确实是一个好方法。特别是无限的油箱,没有停车次数的限制。贪心必选。
这个题的贪心算法主要是用在如何确定起始点上。在程序中用一个tempsum来计算起始点。如果tempsum小于零那么代表之前确定的起始点A并不能到达现在这个点D。。而且,A到D之间的任何一个点起始点都到不了D。因为我们保留A的原则是tempsum要大于等于,代表着A其实的时候,之前加油站的油是够用的且,对以后的行驶有多余的油提供帮助。所以当tempsum小于零的时候代表已经不够用了,就要确定下一个起始点。。
public class Solution { public int canCompleteCircuit(int[] gas, int[] cost) { int sum=0; int index=-1; int temp=0; for(int i=0;i<gas.length;i++) { sum+=(gas[i]-cost[i]); temp+=(gas[i]-cost[i]); if(temp<0) { temp=0; index=i; } } return sum<0?-1:index+1; }}
0 0
- 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】Gas Station
- LeetCode | Gas Station
- LeetCode之Gas Station
- Leetcode: Gas Station
- LeetCode OJ:Gas Station
- [LeetCode]134.Gas Station
- [Leetcode] Gas Station (Java)
- gas station leetcode
- CSS list-style 属性
- WSTMall 微信登录配置
- Qt中文手册 之 QTreeWidgetItem
- 谈论谋略
- 101. Symmetric Tree [easy] (Python)
- leetcode Gas Station
- 自己写的字符处理函数+字符处理函数
- Android多个activity退出问题处理
- JAV开发笔记系列--1-在MAC上利用Android Studio开发JAVA项目
- 通过两个视图监控快速回复区:V$RECOVERY_FILE_DEST and V$RECOVERY_AREA_USAGE.
- C++实验7-函数复习
- iOS学习- 13 删除Table View中的Cell - Todo App
- 不用临时变量交换两个数的值
- 各种基本排序(直接插入;希尔;选择;堆;冒泡;快排)