LeetCode Gas Station
2014-11-06 17:02
246 查看
https://oj.leetcode.com/problems/gas-station/
There are N gas stations along a circular route, where the amount of gas at station i is
You have a car with an unlimited gas tank and it costs
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.
这实际上是一个球最长字序列和大于零的问题,gas[i]的值相当于正数,cost[i]相当于负数,他们交叉组成一个排列。
一开始我用最通俗的方法做,从i开始一直加减数看一下能不能围一圈。这个方法的复杂度是O(2N),最后超时了。
其实这个题可以用动态规划的方法进行解答。如果从rest[I][J]表示从i到j所剩余的油量,如果为负值,那么从I到J的任何一个位置到J,rest的值都是负的。
因为这个位置之前的那些位置必须是gas>=cost才能保证到达该点。从该点到J相当有rest减去gas-cost, 是减去了一个非负值。所以rest不可能为非负的。
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.
这实际上是一个球最长字序列和大于零的问题,gas[i]的值相当于正数,cost[i]相当于负数,他们交叉组成一个排列。
一开始我用最通俗的方法做,从i开始一直加减数看一下能不能围一圈。这个方法的复杂度是O(2N),最后超时了。
public class Solution { public int canCompleteCircuit(int[] gas, int[] cost) { int n = gas.length; int [][]COST = new int ; for(int i=0;i<n;i++) { COST[i][i]=0; } for(int i=0;i<n;i++) { boolean temp = true; for(int j=1;j<=n;j++) { COST[i][(i+j)%n]=COST[i][(i+j-1)%n]+gas[(i+j-1)%n]-cost[(i+j-1)%n]; if(COST[i][(i+j)%n]<0) { temp = false; break; } } if(temp) { return i; } } return -1; } }
其实这个题可以用动态规划的方法进行解答。如果从rest[I][J]表示从i到j所剩余的油量,如果为负值,那么从I到J的任何一个位置到J,rest的值都是负的。
因为这个位置之前的那些位置必须是gas>=cost才能保证到达该点。从该点到J相当有rest减去gas-cost, 是减去了一个非负值。所以rest不可能为非负的。
public class Solution { public int canCompleteCircuit(int[] gas, int[] cost) { int n = gas.length; int rest=0; int head = 0; int length = 0; for(int i=1;i<2*n;i++) { rest += gas[(i-1)%n]-cost[(i-1)%n]; length++; if(length==n)break; if(rest<0) { head = i; rest=0; length = 0; } } if(length==n&&rest>=0&&head<n)return head; return -1; } }
相关文章推荐
- LeetCode(134)Gas Station
- leetcode题目:gas-station 使用start/end方法的个人理解
- [LeetCode] Gas Station
- [LeetCode]Gas Station
- Leetcode 134. Gas Station (Medium) (cpp)
- leetcode---gas-station---贪心
- gas station leetcode
- leetcode:Gas Station 【Java】
- leetcode -- Gas Station
- 【Leetcode】Gas Station #134
- Gas Station(leetcode)
- 【LeetCode练习题】Gas Station
- LeetCode134 Gas Station
- LeetCode Gas Station
- [Leetcode] gas station 气站
- LeetCode题解:Gas Station
- LeetCode134—Gas Station
- Leetcode | Gas Station
- Gas Station——Leetcode系列(十六)
- leetcode——Gas Station