---
title: "[leetcode]Gas Station"
author: "ouqi"
date: "2013-09-30T16:40:49Z"
tags: []
categories: ["编程语言"]
slug: "leetcode-gas-station"
draft: false
lastmod: "2013-09-30T16:41:23Z"
id: 1949560
url: "https://ouqi.iteye.com/blog/1949560"
---

#### Gas Station

 

AC Rate: 296/1493

[](http://oj.leetcode.com/problems/gas-station/submissions/)

 

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.

 

思路：

1 计算c\[i] = gas\[i] - cost\[i] 表示i 到i+1的汽油增量。

2 则本题为：汽车从任意点 i 出发，油量增增减减，但过程中必须保证油量&gt;=0

3 设置delta表示汽车油量，初始为0;  注意到，假设汽车从i点出发，第一次delta+c\[j]&lt;0  (即汽车行至j点与j+1的半路中没油了 ）；则从i+1 到 j 的范围内，以任意一个做为起始点都是不ok的。即下一个可能的起始点从j+1开始。因为： 

       delta+c\[j]第一次小于0， 说明 在i 到 j-1的范围内 delta都是大于0的，若以这中间任意一点m作为起始点，则delta =delta+c\[j] - i到m间的油量（肯定&gt;=0），所以最终delta也是小于0的；

4\. 用于start记录起始点，last记录上一可能的起始点，由上述分析可知 last 至 start-2的范围内肯定是大于等于0的（start-1导致的&lt;0）；所以对于start，需要从start一直循环遍历到last并且加上start-1。

 

代码：

```
public class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        //各种异常
        if(gas == null||cost == null) return -1;
        int len = gas.length;
        if(cost.length!=len) return -1;
        
        int c[] = new int[len];
        for(int i = 0;i<=len-1;i++)
            c[i] = gas[i]-cost[i];
        
        int delta = 0;
        int j = 0;
        int last = 0;
        int start = 0;
        while(start<=len-1&&j<=len-1){
            delta = delta + c[j];
            if(delta<0){
                delta = 0;
                last = start;
                start = j+1; 
            }
            j++;
        }
        if(start == len) return -1;
        //确认以start为开始是否可以跑完全程
        for(int i = 0;i<last;i++) delta = delta+c[i];
        if(start >= 1) delta = delta+c[start-1];
        if(delta>=0) return start;
        return -1;
        
    }
}
```