码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]Gas Station

时间:2016-02-12 17:32:27      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:

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

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

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

标签:

原文地址:http://www.cnblogs.com/dick159/p/5187141.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!