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

LeetCode——Gas Station

时间:2014-07-10 20:59:16      阅读:239      评论:0      收藏:0      [点我收藏+]

标签:leetcode

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;
	}


LeetCode——Gas Station,布布扣,bubuko.com

LeetCode——Gas Station

标签:leetcode

原文地址:http://blog.csdn.net/laozhaokun/article/details/37650317

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