leetcode 134. Gas Station ----- java

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.

1、暴力的做法

public class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int len = gas.length;
int sum = 0;
int[] dp = new int[len];
for( int i = 0;i<len;i++){
dp[i] = gas[i]-cost[i];
sum+=dp[i];
}
int num = 0;
if( sum < 0)
return -1;
for( int i = 0;i<len;i++){
num = 0;
for( int j = i;j<len;j++){
num+=dp[j];
if( num < 0){
break;
}
}
if( num >= 0 )
return i;
} return -1; }
}

2、仔细看题目,发现答案其实是唯一解,那么就只需要从后向前遍历,找到最大子串和的起始位置i,(结束位置是最后一位)

在总消耗>0的前提下,返回起始位置i。

否则返回-1。

public class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) { int len = gas.length;
int sum = 0;
int max = 0;
int start = 0;
for( int i = len-1;i>=0;i--){
sum+=(gas[i]-cost[i]);
if( sum > max ){
max = sum;
start = i;
}
}
if( sum < 0)
return -1;
return start; }
}
上一篇:金融量化分析【day111】:Pandas-时间序列处理


下一篇:iOS 7 Pushing the Limits - Good & Bad Namings in Cocoa