-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode-CarFleet.cpp
More file actions
40 lines (29 loc) · 1012 Bytes
/
LeetCode-CarFleet.cpp
File metadata and controls
40 lines (29 loc) · 1012 Bytes
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
class Solution {
public:
int carFleet(int target, vector<int>& position, vector<int>& speed) {
int n = speed.size();
vector<pair<int, int>> v;
for (int i = 0; i < n; ++i) {
v.push_back({position[i], speed[i]});
}
sort(v.begin(), v.end(), [](auto a, auto b) {
if (a.first == b.first) return a.second < b.second;
return a.first < b.first;
});
vector<double> t(n);
for (int i = 0; i < n; ++i) {
t[i] = (double)(target - v[i].first) / v[i].second;
}
stack<int> s;
int groups = 0;
for (int i = n - 1; i >= 0; --i) {
while (!s.empty() && t[i] > t[s.top()]) {
s.pop();
}
if (i != n - 1 && s.empty()) ++groups;
s.push(i);
}
if (!s.empty()) ++groups;
return groups;
}
};