Gas Station, Leetcode 解题笔记

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.

The solution is guaranteed to be unique.




diff[i] = gas[i] – cost[i] 然后对于这个区间的diff加和,定义

sum[i,j] = ∑diff[k]

如果sum[i,j]小于0,那么这个起点肯定不会在[i,j]这个区间里,跟第一个问题的原理一样。举个例子,假设i是[0,n]的解,那么我们知道 任意sum[k,i-1]肯定是小于0的,否则解就应该是k。同理,sum[i,n]一定是大于0的,否则,解就不应该是i,而是i和n之间的某个点。所以第二题的答案,其实就是在0到n之间,找到第一个连续子序列(这个子序列的结尾必然是n)大于0的。


public class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        int[] diff = new int[gas.length];
        int total_diff = 0;
        int sum = 0;
        int ret = 0;
        for(int i = 0; i < gas.length; i++){
            diff[i] = gas[i] - cost[i];
            total_diff += diff[i];
            sum += diff[i];
            if(total_diff < 0){
                total_diff = 0;
                ret = i+1;
        if(sum < 0) return -1;
        else return ret;

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s