134. 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.
自己写的不太好的解法,借鉴循环数组最大连续和子序列的思想,复杂度O(n);
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost)
{
int len = gas.size(), i, sum=0;
for(i=0; i<len; ++i)
{
sum+=gas[i]-cost[i];
}
if(sum<0)
{
return -1;
}
vector<int> seq1(len), seq2(len);
for(i=0; i<len; ++i)
{
seq1[i] = gas[i]-cost[i];
seq2[i] = cost[i]-gas[i];
}
auto result1=largest_sum_subseq(seq1), result2=largest_sum_subseq(seq2);
if(get<2>(result1) >= sum+get<2>(result2))
{
return get<0>(result1);
cout << get<2>(result1);
}
else
{
return get<1>(result2)+1;
cout << sum+get<2>(result2);
}
}
private:
tuple<int, int, int> largest_sum_subseq(vector<int>& nums)
{
int i, len=nums.size();
int sum=0, sum_min=0, pre_start=-1, start_idx, end_idx, sum_max=-10000000;
for(i=0; i<len; ++i)
{
sum += nums[i];
if(sum_max<sum-sum_min)
{
sum_max=sum-sum_min;
start_idx=pre_start+1;
end_idx = i;
}
if(sum<sum_min)
{
sum_min = sum;
pre_start = i;
}
}
return make_tuple(start_idx, end_idx, sum_max);
}
};
本文介绍了一种解决环形路线上寻找可行起点以完成一圈旅行的问题。通过计算每个加油站的油量与消耗,利用最大连续子序列求和的方法确定是否能从某个加油站出发并返回。该算法复杂度为O(n)。
182

被折叠的 条评论
为什么被折叠?



