-
Notifications
You must be signed in to change notification settings - Fork 0
/
0134.cpp
107 lines (99 loc) · 2.39 KB
/
0134.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#include <iostream>
#include <vector>
using namespace std;
class Solution
{
public:
/*
// 暴力解法
int canCompleteCircuit(vector<int>& gas, vector<int>& cost)
{
int n = gas.size();
int stop;
int remain;
for (int i = 0; i < n; i++)
{
stop = 0;
remain = gas[i];
int Index = i;
if (remain < cost[Index])
continue;
while(stop != n)
{
if (remain >= cost[Index])
{
stop++;
if (Index == n - 1)
{
remain = remain - cost[Index] + gas[0];
Index = 0;
}
else
{
remain = remain - cost[Index] + gas[Index + 1];
Index++;
}
}
else
break;
}
if (stop == n)
return i;
}
return -1;
}
// 贪心(是不是贪心有待考究)
int canCompleteCircuit(vector<int>& gas, vector<int>& cost)
{
int curSum = 0;
int min = INT_MAX;
for (int i = 0; i < gas.size(); i++)
{
int rest = gas[i] - cost[i];
curSum += rest;
if (curSum < min)
min = curSum;
}
if (curSum < 0)
return -1;
if (min >= 0)
return 0;
for (int i = gas.size() - 1; i >= 0; i--)
{
int rest = gas[i] - cost[i];
min += rest;
if (min >= 0)
return i;
}
return +1;
}
*/
// 贪心
int canCompleteCircuit(vector<int>& gas, vector<int>& cost)
{
int curSum = 0;
int totalSum = 0;
int start = 0;
for (int i = 0; i < gas.size(); i++)
{
curSum += gas[i] - cost[i];
totalSum += gas[i] - cost[i];
if (curSum < 0)
{
start = i + 1;
curSum = 0;
}
}
if (totalSum < 0)
return -1;
return start;
}
};
int main()
{
vector<int> gas = { 1,2,3,4,5 };
vector<int> cost = { 3,4,5,1,2 };
Solution S;
S.canCompleteCircuit(gas, cost);
return 0;
}