File tree 1 file changed +28
-28
lines changed
scripts/algorithms/C/Car Fleet
1 file changed +28
-28
lines changed Original file line number Diff line number Diff line change
1
+ // Runtime: 215 ms (Top 30.21%) | Memory: 78.90 MB (Top 67.67%)
2
+
3
+ class Car {
4
+ public:
5
+ Car (int pos, int speed){
6
+ this ->pos = pos;
7
+ this ->speed = speed;
8
+ }
9
+ int pos;
10
+ int speed;
11
+ };
12
+
1
13
class Solution {
2
14
public:
3
15
int carFleet (int target, vector<int >& position, vector<int >& speed) {
4
-
5
- int n = position.size ();
6
- vector<pair<int ,int >> cars;
7
-
8
- for (int i=0 ; i<n; i++)cars.push_back ({position[i], speed[i]});
9
-
10
- sort (cars.begin (),cars.end ());
11
-
12
- int start=0 ;
13
- int mid=0 ;
14
- int fleet = n;
15
-
16
- double times[n];
17
-
18
- for (int i=n-1 ; i>=0 ; i--){
19
- times[i] =((double ) (target-cars[i].first )/cars[i].second );
20
- if (i<n-1 )times[i] = max (times[i],times[i+1 ]);
16
+ vector<Car> cars;
17
+ int N = position.size ();
18
+ for (int i = 0 ; i<N; i++){
19
+ cars.emplace_back (position.at (i), speed.at (i));
21
20
}
22
21
23
- while (mid<n){
24
- double timeA = times[start];
25
- double timeB = times[mid];
26
- // cout<<timeA<<" "<<timeB<<endl;
27
- if (mid-start+1 == 2 ){
28
- if (timeA<=timeB)fleet--;
29
- start++;
22
+ sort (cars.begin (), cars.end (), [](const Car& a, const Car& b){
23
+ return a.pos <b.pos ;
24
+ });
25
+
26
+ stack<float > mono;
27
+ for (int i = 0 ; i<N; i++){
28
+ float time =
29
+ (target-cars.at (i).pos )/(float )cars.at (i).speed ;
30
+ while (!mono.empty () && time >= mono.top ()){
31
+ mono.pop ();
30
32
}
31
- mid++ ;
33
+ mono. push ( time ) ;
32
34
}
33
-
34
- return fleet;
35
-
35
+ return mono.size ();
36
36
}
37
37
};
You can’t perform that action at this time.
0 commit comments