leetcode 1776 - Car Fleet II

https://leetcode.com/problems/car-fleet-ii/

There are n cars traveling at different speeds in the same direction along a one-lane road. You are given an array cars of length n, where cars[i] = [positioni, speedi] represents:

positioni is the distance between the ith car and the beginning of the road in meters. It is guaranteed that positioni < positioni+1.
speedi is the initial speed of the ith car in meters per second.
For simplicity, cars can be considered as points moving along the number line. Two cars collide when they occupy the same position. Once a car collides with another car, they unite and form a single car fleet. The cars in the formed fleet will have the same position and the same speed, which is the initial speed of the slowest car in the fleet.

Return an array answer, where answer[i] is the time, in seconds, at which the ith car collides with the next car, or -1 if the car does not collide with the next car. Answers within 10-5 of the actual answers 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]

Constraints:

1 <= cars.length <= 10^5
1 <= positioni, speedi <= 10^6
positioni < positioni+1

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
27
28
29
30
31
32
33
34
35
36
37
class Solution {
public:
vector<double> getCollisionTimes(vector<vector<int>>& cars) {
int n = cars.size();
stack<int> stk;

vector<double> result(n, -1);

auto collision_time = [&](int a, int b) {
return (double)(cars[b][0] - cars[a][0]) / (cars[a][1] - cars[b][1]);
};

for (int i = n - 1; i >= 0; i--) {
/*不会与i相撞的stk top都可以remove,两种情况
1. stk top速度大于等于i
2. stk top速度小于i,但在i撞到stk top前,stk top已经与它前面的车相撞了
*/
while (!stk.empty()) {
int speed_a = cars[i][1];
int speed_b = cars[stk.top()][1];
if (speed_a <= speed_b || (result[stk.top()] != -1 &&
collision_time(i, stk.top()) > result[stk.top()]))
stk.pop();
else
break;
}

//当前i与stk top相撞
if (!stk.empty())
result[i] = collision_time(i, stk.top());

stk.push(i);
}

return result;
}
};