-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path00853-car_fleet.cpp
56 lines (42 loc) · 1.11 KB
/
00853-car_fleet.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
// 853: Car Fleet
// https://leetcode.com/problems/car-fleet/
#include <iostream>
#include <vector>
#include <algorithm>
#include <stack>
using namespace std;
class Solution {
class car {
public:
car(int p, int s): p(p), s(s) {};
int p;
int s;
};
public:
// SOLUTION
int carFleet(int target, vector<int>& position, vector<int>& speed) {
vector<car> cars;
int n = position.size();
for (int i=0; i<n; i++)
cars.emplace_back(position[i], speed[i]);
sort(cars.begin(), cars.end(), [](const car& a, car& b) {return a.p < b.p;});
stack<float> s;
for (int i=0; i<n; i++) {
float time = (target - cars[i].p) / (float)cars[i].s;
while (!s.empty() && time >= s.top()) s.pop();
s.push(time);
}
return s.size();
}
};
int main() {
Solution o;
// INPUT
int target = 12;
vector<int> position = {10,8,0,5,3};
vector<int> speed = {2,4,1,1,3};
// OUTPUT
auto result = o.carFleet(target, position, speed);
cout<<result<<endl;
return 0;
}