Gas Station

来源:互联网 发布:淘宝客服名 编辑:程序博客网 时间:2024/06/05 16:48

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.

Java代码:

public class Solution {    public int canCompleteCircuit(int[] gas, int[] cost) {        int restGas = 0;int beg = 0;for (int i = 0; i < gas.length; ++i) {restGas += gas[i] - cost[i];if (restGas < 0) {restGas = 0;beg = i + 1; // 找起点时的跳步}}if (beg >= gas.length)return -1;int j = beg, num = 0;restGas = 0;while (num < gas.length) {restGas += gas[j] - cost[j];if (restGas < 0)return -1;num++;j = (j + 1) % gas.length;}return beg;    }}

 

0 0