Skip to content

Commit 091c9da

Browse files
committed
好的想法!
1 parent 2854e9c commit 091c9da

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

small-trick/Gas Station

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
// 这个方法超时了,我还乐滋滋的想出了转一圈的方法 (initial + i) % n == initial, 并且优化,又多加了个confirm 标志,结果。。
2+
// 忘记了转一圈的和就是是否有解的最简便判断!
3+
class Solution {
4+
public:
5+
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
6+
int n = gas.size();
7+
vector<bool> confirm(n,false);
8+
int initial = 0;
9+
int i = 1;
10+
int left = 0;
11+
if(n == 1)
12+
return gas[0] < cost[0]? -1:0;
13+
while((initial + i) % n != initial && initial < n)
14+
{
15+
if(gas[i] >= cost[i])
16+
confirm[i] = true;
17+
if(gas[i] + left < cost[i])
18+
{
19+
while(confirm[++initial]);
20+
i = 1;
21+
}
22+
else
23+
{
24+
left = gas[i] + left - cost[i];
25+
i++;
26+
}
27+
}
28+
if(initial < n)
29+
return initial;
30+
else
31+
return -1;
32+
33+
}
34+
};
35+
36+
//
37+
class Solution {
38+
public:
39+
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
40+
int n = gas.size();
41+
int index = -1;
42+
int curSum = 0;
43+
int total = 0;
44+
for(int i = 0;i < n;i++)
45+
{
46+
curSum += gas[i]-cost[i];
47+
total += gas[i] - cost[i]; // 转一圈有效也就是遍历一遍其值大于等于0!
48+
if(curSum < 0)
49+
{
50+
index = i;
51+
curSum = 0;
52+
}
53+
}
54+
return total >= 0? index + 1: -1;
55+
56+
}
57+
};

0 commit comments

Comments
 (0)