There are n
cars going to the same destination along a one-lane road. The destination is target
miles away.
Each car i
has a constant speed speed[i]
(in miles per hour), and initially present at position position[i]
miles towards the target.
A car can never pass another car ahead of it, but it can catch up to it, and drive bumper to bumper at the same speed. The faster car will slow down to match the slower car’s speed if the cars meet.
The number of car fleets is the total number of groups of cars that are traveling at the same speed.
Given target
, an integer, and two integer arrays position
and speed
, both of length n
, return the number of car fleets.
target = 12, position = [10, 8, 0, 5, 3], speed = [2, 4, 1, 1, 3]
3
n >= 1
.position
and speed
arrays are positive integers.time = (target - position[i]) / speed[i]
import java.util.Arrays;
public class CarFleet {
public int carFleet(int target, int[] position, int[] speed) {
int n = position.length;
if (n == 0) {
return 0;
}
// Create an array of cars with their position and time to reach the target
double[][] cars = new double[n][2];
for (int i = 0; i < n; ++i) {
cars[i][0] = position[i];
cars[i][1] = (double) (target - position[i]) / speed[i];
}
// Sort cars by their starting position
Arrays.sort(cars, (a, b) -> Double.compare(a[0], b[0]));
int fleets = 1;
double curTime = cars[n - 1][1];
for (int i = n - 2; i >= 0; --i) {
if (cars[i][1] > curTime) {
fleets++;
curTime = cars[i][1];
}
}
return fleets;
}
}
n
is the number of cars.Overall, the time complexity is O(n log n).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?