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.
最先想到的方法就是通过begin和end分别指向序列开始和终结,然后就end对应的数据加到sum,如果sum>0,则end递增,反之,则sum减去begin对应的值,begin递增。关于循环终止条件比较复杂,没有办法很好的处理。看别人的代码发现,当sum<0的时候,那么必然是sum1+end<0,此时说明end的值很大,begin递增后sum的值依然为负数,所以直接将begin设为end。通过将所有值相加来判断该题是否有解。
代码如下:
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int num =gas.size();
int sum=0,total=0;
int start=0;
for(int i=0;i<num;i++)
{
total+=gas[i]-cost[i];
if(sum < 0)
{
sum = gas[i]-cost[i];
start=i;
}
else
sum += gas[i]-cost[i];
}
return total<0?-1:start;
}
};
关于自己的最初的解题方法的思考,主要是自己想在一个循环内解决问题,在终止条件的判断上写不出来,如果通过两层循环实现就比较容易,代码如下:
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int begin=0,end=0;
int res = 0;
int num = gas.size();
for(begin =0;begin<num;)
{
res = 0;
for(end=0;end<num;end++)
{
int index = (begin+end)%num;
res += gas[index]-cost[index];
if(res < 0)
{
begin += end+1;
break;
}
}
if(end == num)
return begin;
}
return -1;
}
};
在网上看到一个十分有意思的解题思路,就是通过将该问题转换为求最大子序列和的数学模型。如果要跑完整圈,开始肯定要让自己的油箱里的油越多越好,也就是开始走的一段序列要让自己的油达到顶峰,如果这样都走不完,那么从任何站点出发就都不可能了。通过求出最大子序列和max和最小子序列和min,对于max和total-min的大小,如果max大,则返回最大子序列和的起始位置,否而返回最小子序列的末尾位置加1.这个解题思路对问题进行了剖析,将其转换为了常见的数学问题模型,从而使用动态规划大法求解,十分有益的分析方法.
代码如下:
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int max=gas[0]-cost[0];
int Max=max,min=max,Min=max,total=max;
int maxStart=0,start=0,minEnd=0;
int num = gas.size();
for(int i=1;i<num;i++)
{
int diff = gas[i] - cost[i];
total += diff;
if(max < 0)
{
max = diff;
maxStart = i;
}
else
max += diff;
if(max > Max)
{
Max = max;
start = maxStart;
}
if(min < 0)
{
min += diff;
}
else
min = diff;
if(min < Min)
{
Min = min;
minEnd = i;
}
}
return total<0?-1:((Max>total-Min)?start:(minEnd+1)%num);
}
};