Skip to content

1776. car fleet ii #499

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions Java/CarFleetII.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
class Solution {
public double[] getCollisionTimes(int[][] cars) {
int length = cars.length;
double[] times = new double[length];
Deque<Integer> stack = new LinkedList<Integer>();
for (int i = length - 1; i >= 0; i--) {
while (!stack.isEmpty()) {
if (cars[stack.peek()][1] >= cars[i][1])
stack.pop();
else {
if (times[stack.peek()] < 0)
break;
double time = times[stack.peek()] * (cars[i][1] - cars[stack.peek()][1]);
if (time > cars[stack.peek()][0] - cars[i][0])
break;
else
stack.pop();
}
}
if (stack.isEmpty())
times[i] = -1;
else
times[i] = (double) (cars[stack.peek()][0] - cars[i][0]) / (cars[i][1] - cars[stack.peek()][1]);
stack.push(i);
}
return times;
}
}