You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
LeetCode Records - Question 1279 Traffic Light Controlled Intersection
Attempt 1: Use a LinkedBlockingQueue to track car IDs
classTrafficLight {
privateintroadIdIsGreen;
privateBlockingQueue<Integer> queue;
publicTrafficLight() {
roadIdIsGreen = 1;
queue = newLinkedBlockingQueue();
}
publicvoidcarArrived(
intcarId, // ID of the carintroadId, // ID of the road the car travels on. Can be 1 (road A) or 2 (road B)intdirection, // Direction of the carRunnableturnGreen, // Use turnGreen.run() to turn light to green on current roadRunnablecrossCar// Use crossCar.run() to make car cross the intersection
) {
queue.add(carId);
while (queue.peek() != carId) {}
if (roadIdIsGreen != roadId) {
roadIdIsGreen = roadId;
turnGreen.run();
}
crossCar.run();
queue.poll();
}
}