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

lintcode-medium-Gas Station

时间:2016-03-21 09:25:21      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:

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 costscost[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.

 

Given 4 gas stations with gas[i]=[1,1,3,1], and thecost[i]=[2,2,1,1]. The starting gas station‘s index is 2.

 

public class Solution {
    /**
     * @param gas: an array of integers
     * @param cost: an array of integers
     * @return: an integer
     */
    public int canCompleteCircuit(int[] gas, int[] cost) {
        // write your code here
        
        if(gas == null || gas.length == 0 || cost == null || cost.length == 0 || gas.length != cost.length)
            return -1;
        
        int gas_sum = 0;
        int cost_sum = 0;
        
        for(int i = 0; i < gas.length; i++)
            gas_sum += gas[i];
        
        for(int i = 0; i < cost.length; i++)
            cost_sum += cost[i];
        
        if(gas_sum < cost_sum)
            return -1;
        
        int left = 0;
        int start = 0;
        
        while(start < gas.length){
            int i = start;
            
            for(; i < gas.length; i++){
                left += gas[i];
                left -= cost[i];
                
                if(left < 0){
                    left = 0;
                    break;
                }
            }
            
            if(i != gas.length)
                start = i + 1;
            else
                return start;
        }
        
        return -1;
    }
}

 

lintcode-medium-Gas Station

标签:

原文地址:http://www.cnblogs.com/goblinengineer/p/5300492.html

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