# leetcode-134. 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.

public class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
for(int i = 0; i < gas.length; i++){
int currentGas = gas[i];
int j = i;
while(currentGas >= cost[j]){
//能够到达下一站
currentGas -= cost[j];
j = (j+1) % gas.length;
if(j == i){
return i;
}
currentGas += gas[j];
}
}
return -1;
}
}

public class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int sum = 0;
int total = 0;
int j = 0;
for(int i = 0; i < gas.length; i++){
sum += gas[i] - cost[i];
total += gas[i] - cost[i];
if(sum < 0){
//说明此时汽车无法到达下一站，所以之前所有的i包括当前i都不能作为起点。起点只可能是后面的某个值
j = i + 1;
sum = 0;
}
}
if(total >= 0){
return j;
}else{
return -1;
}
}
}

## [leetcode] 【数组】134. Gas Station

There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. ...

## Leetcode——134. Gas Station && 435. Non-overlapping Intervals

Gas Station 1. 问题描述 有N个加油站围成一个圈，第i个加油站的油量是gas[i]，一辆车有一个无限量的油箱，每次从第i个加油站开到第i+1个加油站需要消耗cost[i]的油量。车一开始...

## leetcode134. Gas Station

134. Gas StationThere are N gas stations along a circular route, where the amount of gas at station ...

## Leetcode-134-Gas Station C#

There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. ...

## [LeetCode]134.Gas Station

【题目】 There are N gas stations along a circular route, where the amount of gas at station i is  Th...

## leetcode || 134、Gas Station

problem： There are N gas stations along a circular route, where the amount of gas at st...

## LeetCode: Gas Station [134]

【题目】 There are N gas stations along a circular route, where the amount of gas at station i is gas[i...

举报原因： 您举报文章：深度学习：神经网络中的前向传播和反向传播算法推导 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)