Leecode Gas Station

/**
 * 
 * @author LP
 * 简单贪心算法
 * 1、先算出每走一个加油站加的油与消耗的差值
 * 2、如果所有差值之和大于0的话就存在解,且题目保证解唯一
 * 3、2满足,则循环差值之和,前面如果为正对后面是更多油量。如果为负表示到不了,另起新点。
 * 4、2不满足返回-1
 * 
 */
/* 测试用例
 * int cost[]={3,5,5,3,1};
 * int gas[]={8,1,1,2,5};*/

/*int cost[]={5,5,5,3,1};
 * int gas[]={3,1,1,2,5};*/
class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
    	
    	int sum=0;
    	int len;
    	len = gas.length;
    	int[] temp = new int[len];
    	int result,t;
    	for(int i=0;i<len;i++){
    		temp[i]=gas[i]-cost[i];
    		sum+=temp[i];
    	}
    	if(sum>=0){
    		result = 0;
    		t=0;
    		for(int i=0;i<len;i++){
    			if((t+=temp[i])>=0){
    				continue;
    			}
    			else{
    				t=0;
    				result = i+1;
    			}
    		}
    		return result;
    	}
    	else return -1;
        
    }
}

你可能感兴趣的:(LeetCode,算法,贪心)