[LeetCode] Car Fleet

853. Car Fleet

There are n cars going to the same destination along a one-lane road. The destination is target miles away.

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).

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).

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.

If a car catches up to a car fleet right at the destination point, it will still be considered as one car fleet.

Return the number of car fleets that will arrive at the destination.

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
class Solution {
double arrviveTime(int target, int cur, int speed) {
return (target - cur) * 1.0 / speed;
}
public:
int carFleet(int target, vector<int>& position, vector<int>& speed) {
vector<pair<int,int>> order;
for(int i = 0; i < speed.size(); i++) {//o(n)
order.push_back({position[i], speed[i]});
}
sort(order.begin(), order.end()); //o(nlogn);

//arrivetime
double dp = arrviveTime(target, order.back().first, order.back().second);
int res = 1;
for(int i = position.size() - 2; i >= 0; i--) {
double arvTime = arrviveTime(target, order[i].first, order[i].second);
if(arvTime > dp) {
dp = arvTime;
res++;
}
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/18/PS/LeetCode/car-fleet/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.