<leetcode> Gas station
来源:互联网 发布:淘宝联名信用卡怎么用 编辑:程序博客网 时间:2024/05/17 21:41
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.
思路来源于水中的鱼
新建一个油耗数组diff[], 赋值为diff[i]=gas[i]-cost[i] 若存在解,则证明diff[]的和为正值(总补给大于总消耗),若diff[]和为负值,证明无解(消耗大于补给)
设解为k(唯一),则diff[]中从k到diff.length-1的和为正值(可以从k走到最后), 并且对于其中任意一个点n,k到n的和均为正值(否则k无法到n)
设一个sum=sum+diff[i],当sum小于0的时候从当前位置从新开始计算(sum=0,start=i+1)直到找到一个k使k到(diff.size-1)的和为正值。如果没有返回-1;
找到k后同时需要确定是否有解(即k能否从length-1走到k(loop)),若diff[]和为正则证明有解,k为唯一解,若为负证明无解返回-1
public class Solution { public int canCompleteCircuit(int[] gas, int[] cost) { int[] diff=new int[gas.length]; for(int i=0;i<gas.length;i++){ diff[i]=gas[i]-cost[i]; } int leftGas=0; int sum=0; int start=0; for(int i=0;i<gas.length;i++){ leftGas+=diff[i]; sum+=diff[i]; if(sum<0){ sum=0; start=i+1; } } if(start>=gas.length){ return -1; } else if(leftGas<0){ return -1; } else return start; }}
- 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
- 第一次用阿里云ecs配置pptp vpn遇到的问题。
- f68;f86f7lfd865rf7l658
- struct 结构体的大小
- 的发货他并恢复后太阳能今天就白居易
- 关于das
- <leetcode> Gas station
- 用PGCL为安卓编写有效的OpenCL代码
- Objective-C入门
- <leetcode>Container With Most Water
- c++重载ostream的实现
- 会计法开始减肥可适当分开
- Ubuntu系统下如何在不重启的情况下修改hostname
- 代码面试题:Find two smallest number of an array
- poj 1953 Team Rankings