gas-station Java code

来源:互联网 发布:数据透视表 值 合计 编辑:程序博客网 时间:2024/06/13 09:33

There are N gas stations along a circular route, where the amount of gas at station i isgas[i].
You have a car with an unlimited gas tank and it costscost[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.

思路:统计全程走完油是否耗尽。没耗尽,就在remain出现小于零的地方作为开始。

public class Solution {    public int canCompleteCircuit(int[] gas, int[] cost) {        if (gas == null || cost == null || gas.length <= 0 || cost.length <= 0)            return -1;        int index = -1, remain = 0, total = 0;        for(int i = 0; i < gas.length; i++){            total += gas[i] - cost[i];            remain += gas[i] - cost[i];            // 如果本次剩余<0,说明不能由i走到i+1            if(remain < 0){                remain = 0;                index = i;            }        }        return total >= 0 ? index + 1 : -1;    }}
原创粉丝点击