leetcode--17. 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.

沿环形路线有N个加油站,其中第 i 站的煤气量为gas[ i ]。你有一辆有一个无限制油箱的汽车,从 i 站到下一站(i+1)要花费大量的汽油。你从一个加油站并且初始油箱为空开始旅程。如果你可以绕环路一次,返回启程加油站的索引,否则返回-1。
注意:解决方案保证是唯一的。

思路:
用最后一个点作为起点,当油量够时则end++,当油量不够就start后退一个直至到0,换起点后不需计算后续点,只需要计算刚才结余即可

public class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int start = gas.length - 1;
        int end = 0;
        int sum = gas[start] - cost[start];
        while(start > end){
            if(sum > 0){
                sum += gas[end] - cost[end];
                end++;
            } else {
                start--;
                sum += gas[start] - cost[start];
            }
        }
        return sum >= 0 ? start : -1;
    }
}

你可能感兴趣的:(leetcode--17. gas-station)