LeetCode Gas Station
来源:互联网 发布:街头篮球刷数据 编辑:程序博客网 时间:2024/06/05 16:37
题意:
给定一个[0,n)的gas station,每个站可以加gas[i],然后才从每个站到下一个站需要cost[i]的gas cost,问从哪个节点可以绕转一圈
解法:
首先既然是可以转圈的,那么唯一不成立的情况就是gas和比cost和小,否则都能够“转”出结果来。可能略微抽象,大家仔细想想。证明我也不会囧……
然后就是很明显的贪心了,到了一个gas station就把gas[i]加满,然后再扣掉下面的cost[i],累加,只要转一圈能大于0即可。
这么一听是不是感觉很像最大区间和呢?不过这里不用求最大区间和,而是最大区间和能否大于0并且横跨整个长度l。
吐槽:
题目中没有说明顺时针还是逆时针,做法其实是一样的。我试了一下,都是默认顺时针的结果,不过为了更加的trivial,我都写了~
public class Solution {int clockwise[];int counterclockwise[];int l;public int canCompleteCircuit(int[] gas, int[] cost) {l = gas.length;int s = 0;for (int i = 0; i < l; i++)s += gas[i] - cost[i];if (s < 0)return -1;clockwise = new int[l];counterclockwise = new int[l];for (int i = 0; i < l; i++)clockwise[i] = gas[i] - cost[i];for (int i = 1; i < l; i++)counterclockwise[i] = gas[i] - cost[i - 1];counterclockwise[0] = gas[0] - cost[l - 1];int sum = 0, index = 0;for (int i = 0; i < l * 2; i++) {if (i - l == index)return index % l;if (sum + clockwise[i % l] < 0) {index = (i + 1) % l;sum = 0;} else {sum += clockwise[i % l];}}sum = 0;index = 2 * l - 1;for (int i = l * 2 - 1; i >= 0; i--) {System.out.println(i + " --- " + index + " " + sum);if (i + l == index) {return index % l;}if (sum + counterclockwise[i % l] < 0) {index = (i - 1) % l;i--;sum = 0;} else {sum += counterclockwise[i % l];}}return -1;}public static void main(String[] args) {int a[] = new int[] { 2, 3, 1 };int b[] = new int[] { 3, 1, 2 };Solution s = new Solution();System.out.println(s.canCompleteCircuit(a, b));}}
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
- SQLMap用户手册【超详细】
- Android最佳性能实践(四)——布局优化技巧
- ios状态栏颜色的设置(背景、前景)
- 经典SQL语句大全
- CRONJOB 无法起作用
- LeetCode Gas Station
- 在Eclipse里面启动tomcat服务器出现Server Tomcat v8.0 Server at localhost failed to start.问题
- 更改安卓系统的版本号
- ETL学习笔记之三 工具篇(转)
- 安卓有些监听程序2.3可运行,4.0往上不可以运行
- KMP算法详解
- UIView和CALayer的详解
- Afinal图片下载例子
- 修改Android系统版本号