-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLC_1776.java
47 lines (40 loc) · 1.43 KB
/
LC_1776.java
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
38
39
40
41
42
43
44
45
46
47
package leetcode;
import java.util.Stack;
class LC_1776 {
public double[] getCollisionTimes(int[][] cars) {
double[] ans = new double[cars.length];
Stack<CarInfo> stack = new Stack<>();
for(int i=cars.length-1;i>=0;i--) {
while(!stack.empty()) {
CarInfo rightCarInfo = stack.peek();
if(rightCarInfo.spd >= cars[i][1]) {
stack.pop();
} else {
double currCollideTime = (double)(rightCarInfo.pos - cars[i][0])/
(cars[i][1] - rightCarInfo.spd);
if(rightCarInfo.collideTime >= currCollideTime) {
stack.push(new CarInfo(cars[i][0],cars[i][1], currCollideTime));
ans[i] = currCollideTime;
break;
} else {
stack.pop();
}
}
}
if(stack.empty()) {
stack.push(new CarInfo(cars[i][0], cars[i][1],Double.MAX_VALUE));
ans[i] =-1;
}
}
return ans;
}
class CarInfo {
int pos, spd;
double collideTime;
public CarInfo(int pos, int spd, double collideTime) {
this.pos = pos;
this.spd = spd;
this.collideTime = collideTime;
}
}
}