Leetcode:Gas Station

来源:互联网 发布:淘宝刷单改价格安全吗 编辑:程序博客网 时间:2024/06/06 02:00

URL

https://leetcode.com/problems/gas-station/description/

描述

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.

代码

class Solution {    public int canCompleteCircuit(int[] gas, int[] cost) {        int len = gas.length;        int[] diff = new int[len];        for(int i=0;i<len;i++){            diff[i] = gas[i] - cost[i];        }        int sum = diff[0];        int begin = 0,end = 0;        for(int i=1;i<len;i++){            if(sum>=0){                end++;                sum+=diff[end];            }else {                begin--;                if(begin<0) begin+=len;                sum+=diff[begin];            }        }        return sum<0?-1:begin;    }}
原创粉丝点击