Gas Station 加油站问题【oj】

问题描述:

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. sum(gas-cost)>= 0时一定有解;2.向前累积和,如果某个位置的和为负,则该解一定在其后。

问题可以转换为求rest[i] = gas[i] - cost[i] + rest[i-1],每一次遇到rest[i] < 0;则舍弃前面的部分,从i+1继续统计,使得从该位起其后的rest为正。

时间复杂度为O(n),为了节省空间,所以不需要rest数组,直接使用rest。

相关代码:

 int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
        	int size = gas.size();
        	int total = 0;
        	int rest = 0;
        	int end = -1; //最后一个rest为负的位置
        	for(int index = 0; index < size; index++)
        	{
        		rest += gas[index] - cost[index];
        		total += gas[index] - cost[index];
        		if(rest < 0)
        		{
        			end = index;
        			rest = 0;
        		}
        	}
        	if(total < 0 ) return -1;
        	else return end + 1;
        
    }

个人感想:这个题真的很考逻辑,核心:需要知道total > 0 时一定有解,又由于解唯一,所以累计和为负则前面的index均不可能作为起始点,重新累计。个人觉得是找到数组中子序列和最大的变形。嘻嘻加油!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值