Skip to content

Commit 1c3803c

Browse files
committed
Runtime: 215 ms (Top 30.21%) | Memory: 78.90 MB (Top 67.67%)
1 parent 488b374 commit 1c3803c

File tree

1 file changed

+28
-28
lines changed

1 file changed

+28
-28
lines changed
+28-28
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,37 @@
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+
113
class Solution {
214
public:
315
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));
2120
}
2221

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();
3032
}
31-
mid++;
33+
mono.push(time);
3234
}
33-
34-
return fleet;
35-
35+
return mono.size();
3636
}
3737
};

0 commit comments

Comments
 (0)