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.
Note:
The solution is guaranteed to be unique.
二、输入输出
输入gas cost数组,输出起始位置的index
三、解题思路
题目最佳解法是时间复杂度为o(n),虽然归类是greedy,但是看高分solution也没看到贪心,这里就给出一般的array解法吧,像是个智力题一样。。
思路一:时间复杂度为o(n)
首先我们可以把gas[i] - cost[i]放到一个数组gasMinusCost里,有正有负。为正说明从i出发到i+1 gas是用不完的。为负说明单纯靠i提供的gas 是无法到达i+1节点的。 那么如果gasMinusCost的和为负,则说明所有站点提供的gas都不够用,肯定无法绕一圈,返回-1;
如果为正,说明是肯定有解的,而且start位置对应的gasMinusCost[start]必须非负。又因为题目说了解时单一的,那么我们可以从第一个start位置开始遍历,记录走到当前节点的gasMinusCost和,如果为正则说明可以走到这个节点,如果为负,则说明从start 节点出发,无法走到这个节点。下面重点来了,有一条性质需要我们想清楚:
如果从start不能走到index,那么从[start, index)中间的任何一个位置出发都无法到达index这个节点。因为index是从start出发以来,第一个为负的节点,前面的都为正。任取一个节点 i range in [start, index) 那么都有sum[i] >=0 而且sum[i-1]>=0 那么[start, i-1]这些节点对i节点提供的都是正的gas,不会出现负的。如果多给你一些gas你都无法从i走不到index,那么不给你让你从i 更不可能走到index了
有了这个发现,就可以写出o(n)的程序了。既然从[start, index) 都不能走到index。那么我们只好从index+1继续出发了。然后重复这个步骤,因为肯定有解,所以只需要遍历一遍就可以了。
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
vector<int> gasMinusCost;
for (int i = 0, n = gas.size(); i < n; ++i) {
gasMinusCost.push_back(gas[i] - cost[i]);
}
if(accumulate(gasMinusCost.begin(), gasMinusCost.end(), 0) < 0)return -1;
int sum = 0, start = 0;
for (int j = 0; j < gasMinusCost.size();) {
sum += gasMinusCost[j];
if(sum < 0){start = j+1;sum = 0;}
j++;
}
return start >= gasMinusCost.size() ? -1 : start;
}
};
思路二:时间复杂度为O(n2)
- 刚开始因为没有发现上面这个规律,所以写了个n2的程序,结果TEL了。看了下所有的16个case倒是全部通过了,所以还是把程序贴出来。
- 思路跟上面差不多,也是挨个遍历。只是发现sum为负的时候,继续从start+1开始
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
vector<int> gasMinusCost;
for (int i = 0, n = gas.size(); i < n; ++i) {
gasMinusCost.push_back(gas[i] - cost[i]);
}
if(accumulate(gasMinusCost.begin(), gasMinusCost.end(), 0) < 0)return -1;
for (int i = 0,n = gasMinusCost.size(); i < n; ++i) {
if(gasMinusCost[i] < 0)continue;
else {
//假设从i开始往前走,看能不能走一圈
int leftGas = gasMinusCost[i], cnt;
for (cnt = 1; cnt < n; ++cnt) {
int j = (i+cnt) % n;
leftGas += gasMinusCost[j];
if(leftGas < 0)break;
}
if(cnt == n)return i;
}
}
return -1;
}
PS:这些类似的规律,一直都发现不到。是自己太笨了吗?还是做题做的少拿?