[LeetCode]Gas Station

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode]Gas Station相关的知识,希望对你有一定的参考价值。

新年啦,大家新年快乐~~

由于新年呢,所以最近很少做题,今天终于有时间可以打打代码了

134. 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.

 

比较简单的题目,只要想到一个策略就好了.(貌似是贪心?)

上代码了,其实主要思想就是看下当前的汽油够不够用.

public class Solution {

    public int canCompleteCircuit(int[] gas, int[] cost) {
        int g=0;
        int c=0;
        int tg=0;
        int tc=0;
        int ret=0;
        boolean flag = false;
        for(int i=0;i<cost.length;i++){
            g+=gas[i];
            c+=cost[i];
            
            tg+=gas[i];
            tc+=cost[i];
            if(gas[i]>cost[i] && !flag){
                ret = i;
                flag = true;
            }
            if(tg<tc){
                tg=0;
                tc=0;
                flag = false;
            }
        }
        if(c<=g) return ret;
        return -1;
    }

    public static void main(String[] args) {
      Solution s = new Solution();
      int[] gas = new int[]{2};
      int[] cost = new int[]{2};
      System.out.println(s.canCompleteCircuit(gas, cost));
    }
}

 

以上是关于[LeetCode]Gas Station的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode]题解(python):134-Gas Station

LeetCode-134-Gas Station

Leetcode 134 Gas Station

[leetcode-134-Gas Station]

算法Gas Station(LeetCode134)

算法Gas Station(LeetCode134)