#1776

Car Fleet II

expert · 1230 · lc hard +32 · verified · 57.8% accepted · 965 likes · top 54%

Description

There are n cars on a single-lane road with cars[i] = [positioni, speedi] (positions strictly increasing). When a faster car catches a slower car they form a fleet at the slower speed. Return answer[i] = the time car i collides with the next car ahead, or -1 if never. Answers within 10-5 are accepted.

Example 1:

Input: cars = [[1,2],[2,1],[4,3],[7,2]]
Output: [1.00000,-1.00000,3.00000,-1.00000]
Explanation: After exactly one second, the first car will collide with the second car, and form a car fleet with speed 1 m/s. After exactly 3 seconds, the third car will collide with the fourth car, and form a car fleet with speed 2 m/s.

Example 2:

Input: cars = [[3,4],[5,4],[6,3],[9,1]]
Output: [2.00000,1.00000,1.50000,-1.00000]

Code

1
2
3