第六周作业:
134. Gas Station
解题思路:
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.
思路:一道动态规划的题目。现在定义diff[i]=gas[i]-cost[i],表示经过i点加油并行驶后,油量的增加量(负值则代表减少)。首先传统的思路就是,每个点逐点计算,看是否有满足条件的点存在,这样的复杂度是O(n²)。在这个过程中,有很多重复计算的过程,因此要将算法进行优化。一个可行的优化方法就是,从起始点i=0出发,累加diff值sum,当行驶至i=k点时sum<0,则表明,在k0到k点这一段路程中,肯定能顺利完成行驶。因此可以不予考虑这一段路程。然后再从k点作为起点出发。这样就能将整段路程分为很多个sum,最多有且只有一个sum是不小于0的。我们从不小于0的那个点出发,如果加上其他的sum,仍能保证不小于0,那么就说明可以完成这个路程,且起点就为不小0的sum所开始的那个点,否则一定无法驶完全程。
不过这里有一个简单的方法就是,在遍历的过程中,直接用一个变量将diff累加起来,这样只需最后判断diff的值是否小于0即可。sum只用作判断哪个点作为起点最合适。
代码如下:
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
vector<int> diff;
if(gas.size()!=cost.size()||!gas.size()||!cost.size())
return -1;
for(int i=0;i<gas.size();i++){
diff.push_back(gas[i]-cost[i]);
}
int total=0,flag=0,sum=0;
for(int i=0;i<diff.size();i++){
total+=diff[i];
if(sum<0){
sum=diff[i];
flag=i;
}
else
sum+=diff[i];
}
return total<0?-1:flag;
}
};