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.

解题思路:

使用贪心的思想,首先遍历gas station,找到第一个满足条件:gas[i]>=cost[i]的gas station,
gas[i]>=cost[i]说明从当前gas station可以到达下一个gas station,
然后从该gas station i 开始,计算能否走一圈。如果可以编号i即为所求;
否则找到gas station i后面的第一个满足条件:gas[j]<cost[j]的gas station,然后找到
gas station j后面的第一个满足条件:gas[k]>=cost[k]的gas station即为下一个可以计算能否走一圈的开始位置。
这样做的目的是跳过连续的满足条件:gas[i]>=cost[i]的gas station,因为如果从满足这个条件的gas station的第一个
位置处开始都不能走一圈,那么从满足这个条件的后面连续的任何一个开始都不可能走一圈。


AC代码如下:

class Solution {
public:
	int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
		int n = gas.size();
		if (n == 0) return 0;
		for (int i = 0; i < n;){
			if (gas[i] >= cost[i]){
				int pre = gas[i] - cost[i];
				int j = i + 1;
				for (; j < n; ++j){        //找到gas station i后面的第一个满足条件:gas[j]<cost[j]的gas station
					if (gas[j] < cost[j])
						break;
				}
				for (int k = i + 1; k < n; ++k){//从gas station i 开始,计算能否走一圈
					pre = pre + gas[k] - cost[k];
					if (pre < 0){
						break;
					}
				}
				if (pre < 0){ //如果从gas station i 开始不能走一圈,跳过i后面连续的满足条件:gas[i]>=cost[i]的gas station
					i = j + 1;
					continue;
				}
				for (int k = 0; k < i; ++k){//如果从gas station i 开始不能走一圈,跳过i后面连续的满足条件:gas[i]>=cost[i]的gas station
					pre = pre + gas[k] - cost[k];
					if (pre < 0) break;
				}
				if (pre < 0){
					i = j + 1;
					continue;
				}
				else return i;
			}
			else{
				++i;
			}
		}
		return -1;
	}
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值