【leetcode】 gas-station 加油站问题

题目描述:

环形路上有n个加油站,第i个加油站的汽油量是gas[i]。你有一辆车,车的油箱可以无限装汽油。从加油站i走到下一个加油站(i+1)花费的油量是cost[i],你从一个加油站出发,刚开始的时候油箱里面没有汽油。求从哪个加油站出发可以在环形路上走一圈。返回加油站的下标,如果没有答案的话返回-1。

注意:答案保证唯一。

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.

Note: The solution is guaranteed to be unique.

问题分析:

1、通过所有加油站的汽油量总和减去花费油量总和,可以判断是否可以在环形路上走一圈,如果不可以,那么返回-1;

2、假设到达第i个加油站的剩余油量为sum,那么加上第i个加油站的汽油量gas[i]再减去走到下一站(i+1)花费的油量cost[i],可判断从第i个加油站是否可以到达下一个加油站;

3、如果当前位置不支持继续前进,那么换下一个加油站作为出发点;

4、如果有解,那么是唯一解,返回加油站的位置(从1开始计数)。

算法分析:

可以运用贪心的思想解决该问题,核心是start的寻找。从第一个加油站开始,如果遇到不符合要求,那么从不符合要求位置的加油站开始,鉴于前面的计算,可知第一个加油站到该位置可达,如果从该位置出发可以走到终点说明可以在环形路上走一圈。算法时间复杂度为O(n)。

编码实现:

public class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int sum = 0, start = -1, total = 0;
		for( int i=0; i<gas.length; i++) {
			sum += gas[i]-cost[i];
			total += gas[i]-cost[i];
			if(sum<0) {
				sum = 0;
				start = i;
			}
		}
		return total>=0 ? start+1:-1;
    }
}

猜你喜欢

转载自blog.csdn.net/VinWqx/article/details/104907324