首页 > 代码库 > LeetCode——Gas Station

LeetCode——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.

Note:

The solution is guaranteed to be unique.

原题链接:https://oj.leetcode.com/problems/gas-station/

题目:在一个环上有N个加油站,站 i 有 gas[i] 的油。

你有一辆汽车有无限大小的油箱,它从站 i 到站 i+1 要耗cost[i] 的油。你以空油箱从其中的一个站出发。如果你转了一圈,返回起始油站的索引,否则返回-1.

思路:先计算车到达每个加油站时加油站的油量和汽车消耗的油量之差,如果之差小于0,则说明汽车至少要从下一站出发,因为从本站出发的话,就到达不了下一站。如果总的之差小于0,则车无法完成一圈。

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