853 Car Fleet
853. Car Fleet
1. Question
N
cars are going to the same destination along a one lane road. The destination istarget
miles away.
Each cari
has a constant speedspeed[i]
(in miles per hour), and initial positionposition[i]
miles towards the target along the road.
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 distance between these two cars is ignored - 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. How many car fleets will arrive at the destination?
Example 1:
0 <= N <= 10 ^ 4
0 < target <= 10 ^ 6
0 < speed[i] <= 10 ^ 6
0 <= position[i] < target
All initial positions are different.
2. Implementation
(1) TreeMap
思路: 题目给定两个数组,一个是position代表每个车的初始位置,另一个是speed代表每个车的速度,问这些车从各自的位置到target位置中,有多少个car fleet(类似于车堵成一个cluster)。题目限制是只有一条路,而且不能超车,所以在前面跑得慢的车会堵住后面速度更快的车。
解法是将这些车按照位置从大到小排序(在treeMap中,我们存位置的负数,已达到从大到小排序的效果), 然后计算每个车到target所需要的时间。按照车从大到小的位置,记录当前到target所需的最大时间,如果某车到达目的地所需的时间大于当前最大时间,则说明有车比当前的车都慢,新的cluster出现。
3. Time & Space Complexity
TreeMap: 时间复杂度O(nlogn), 空间复杂度O(n)
Last updated
Was this helpful?