原题链接:Leetcode 134. 加油站
我屎一样的代码。。。面向测试样例的编程
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int start = -1;
int n = cost.size();
vector<int> tonext(n);
int all = 0, cnt0 = 0;
for (int i = 0; i < n; i++) {
tonext[i] = gas[i] - cost[i];
all += tonext[i];
if (tonext[i] == 0)
cnt0++;
}
if (all < 0)
return start;
if (cnt0 == n)
return 0;
vector<int> left(n);
vector<int> right(n);
for (int i = 1; i < n; i++) {
left[i] = left[i - 1] + tonext[i - 1];
}
right[n - 1] = tonext[n - 1];
for (int i = n - 2; i >= 0; i--) {
right[i] = right[i + 1] + tonext[i];
}
for (int i = 0; i < n; i++) {
if (tonext[i] <= 0 || right[i] < 0)
continue;
int tmp = 0;
for (int j = i; j < n; j++) {
if (tmp < 0)
break;
tmp += tonext[j];
}
if (tmp >= 0)
return i;
}
return start;
}
};
官方题解思路: 如果从x
出发最多能到y
,那么x到中间的所有位置(假设有cnt
个),最多也只能到y
,那么就忽略从这些地方出发的可能,下一次的出发点本来应该是x+1
,现在直接为x+1+cnt
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int n = cost.size();
int i = 0;
while (i < n) {
int cnt = 0;
int sumgas = 0;
int sumcost = 0;
int now = i;
while (cnt < n) {
sumgas += gas[now];
sumcost += cost[now];
if (sumgas < sumcost)
break;
cnt++;
now = (now + 1) % n;
}
if (cnt == n)
return i;
else
i = i + cnt + 1;
}
return -1;
}
};