LeetCode 134. Gas Station
Solution1:我的答案,无数次试错得到的,不成系统,没有思路。。
时间复杂度
O(n2)
O
(
n
2
)
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int i = 0, amount_gas = 0, n = gas.size();
if (n <= 1) {
if(n == 0)
return -1;
if (gas[0] >= cost[0])
return 0;
else
return -1;
}
while (i < n) {
if (gas[i] < cost[i])
i++;
else {
int j = i;
amount_gas = gas[j];
for (j = (i + 1)%n; j != i%n; j = (j + 1)%n) {
int temp = ((j - 1)%n + n)%n;
if (amount_gas - cost[temp] >= 0)
amount_gas = amount_gas - cost[temp] + gas[j];
else
break;
if (j == ((i - 1)%n + n)%n) {
if (amount_gas - cost[j] >= 0)
return i;
else
break;
}
}
i++;
}
}
return -1;
}
};
Solution2:
参考网址:http://www.cnblogs.com/grandyang/p/4266812.html
时间复杂度
O(n)
O
(
n
)
我们首先要知道能走完整个环的前提是gas的总量要大于cost的总量,这样才会有起点的存在。假设开始设置起点start = 0, 并从这里出发,如果当前的gas值大于cost值,就可以继续前进,此时到下一个站点,剩余的gas加上当前的gas再减去cost,看是否大于0,若大于0,则继续前进。当到达某一站点时,若这个值小于0了,则说明从起点到这个点中间的任何一个点都不能作为起点,则把起点设为下一个点,继续遍历。当遍历完整个环时,当前保存的起点即为所求。代码如下:
奇技淫巧!奇技淫巧啊!
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int total = 0, sum = 0, start = 0;
for (int i = 0; i < gas.size(); ++i) {
total += gas[i] - cost[i];
sum += gas[i] - cost[i];
if (sum < 0) {
start = i + 1;
sum = 0;
}
}
return (total < 0) ? -1 : start;
}
};