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 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.
一开始我用最通俗的方法做,从i开始一直加减数看一下能不能围一圈。这个方法的复杂度是O(2N),最后超时了。
public class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int n = gas.length;
int [][]COST = new int [n][n];
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上的加油站问题提供了一种高效的解决方案。通过避免超时的方法,文章首先介绍了传统方法存在的问题,随后提出了一种利用动态规划的思想来解决该问题的新思路。这种方法通过计算从起点到每个站点的剩余油量,确保能够完成整个环路。
1005

被折叠的 条评论
为什么被折叠?



