LeetCode134.加油站
题目
代码
public class Solution
{
public int CanCompleteCircuit(int[] gas, int[] cost)
{
int count = gas.Length;
int[] cost1 = new int[2 * count];
for (int k = 0; k < count; k++)
cost1[k] = cost[k];
for (int k = count; k < 2 * count; k++)
cost1[k] = cost[k - count];
int[] gas1 = new int[2 * count];
for (int k = 0; k < count; k++)
gas1[k] = gas[k];
for (int k = count; k < 2 * count; k++)
gas1[k] = gas[k - count];
for (int i = 0; i < count; i++)
{
if (gas[i] < cost[i]) //第一段路程的消耗大于第一个加油站的油数,则第一站无法到达,因此不能从此站出发
continue;
int total = gas1[i]; //在第一站加油
int j;
for (j = i; j <count + i - 1; )
{
total = total - cost1[j] + gas1[j+1]; //到达此站加完油后总共的油数
j++;
if (total < cost1[j])
break;
}
if (total >= cost1[j])
return i;
}
return -1;
}
}
太过于冗杂,优化
public class Solution
{
public int CanCompleteCircuit(int[] gas, int[] cost)
{
int count = gas.Length;
int total = 0;
int sum = 0;
int start = 0;
for(int i = 0; i < count; i++)
{
sum += gas[i] - cost[i];
total += gas[i] - cost[i];
if(sum < 0)
{
start = i + 1;
sum = 0;
}
}
return total < 0 ? -1 : start;
}
}