Skip to content

Commit 1039a6c

Browse files
authoredAug 29, 2023
853. Car Fleet I
1 parent 76c4ee8 commit 1039a6c

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
 

‎853. Car Fleet I

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/*There are n cars going to the same destination along a one-lane road. The destination is target miles away.
2+
3+
//You are given two integer array position and speed, both of length n, where position[i] is the position of the ith car and speed[i] is the speed of the ith car (in miles per hour).
4+
5+
//A car can never pass another car ahead of it, but it can catch up to it and drive bumper to bumper at the same speed. The faster car will slow down to match the slower car's speed. The distance between these two cars is ignored (i.e., they are assumed to have the same position).
6+
7+
//A car fleet is some non-empty set of cars driving at the same position and same speed. Note that a single car is also a car fleet.
8+
9+
//If a car catches up to a car fleet right at the destination point, it will still be considered as one car fleet.
10+
11+
//Return the number of car fleets that will arrive at the destination.
12+
13+
14+
15+
16+
class Solution {
17+
class Car{
18+
public:
19+
int pos,speed;
20+
Car(int p,int s):pos(p), speed(s){};
21+
};
22+
static bool mycomp(Car&a,Car&b){
23+
return a.pos<b.pos;
24+
}
25+
public:
26+
int carFleet(int target, vector<int>& position, vector<int>& speed) {
27+
vector<Car>cars;
28+
for(int i=0;i<position.size();i++){
29+
Car car(position[i],speed[i]);
30+
cars.push_back(car);
31+
}
32+
sort(cars.begin(),cars.end(),mycomp);
33+
stack<float>st;
34+
for(auto car:cars){
35+
float time = (target-car.pos)/((float)car.speed);
36+
37+
while(!st.empty() && time>= st.top()){
38+
st.pop();
39+
}
40+
st.push(time);
41+
}
42+
return st.size();
43+
}
44+
};
45+
46+
//medium but tough though

0 commit comments

Comments
 (0)
Please sign in to comment.