[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));
    }
}

 

posted @ 2016-02-12 17:09  hudiwei-hdw  阅读(122)  评论(0编辑  收藏  举报