853. Car Fleet
use sort, when there is a new slower one means a new fleet
由題目得知, 夠快的車, 就會跟現在有車隊變同一個,
所以反過來說, 慢的車, 會自成一個車隊, 所以可以利用這點來做
位置當然要排序過才好做
T:O(nlogn)
S: O(n)
class Solution {
public int carFleet(int target, int[] position, int[] speed) {
int n = position.length;
double[][] data = new double[n][2];
for (int i = 0; i < n; i++) {
data[i][0] = position[i];
data[i][1] = (double)(target - position[i])/speed[i];
}
Arrays.sort(data, (a,b) -> Double.compare(a[0], b[0]));
double currBiggestTime = 0;
int fleet = 0;
for (int i = n-1; i >= 0; i--) {
if (data[i][1] > currBiggestTime) {
currBiggestTime = data[i][1];
fleet++;
}
}
return fleet;
}
}
/*
(destination - position)/speed = time to destination
1.
so if 2 cars time to destination, are == or 1 car is faster,
they will run together(become same fleet, fleet doesnt change) to destination
2.
so if one car is slower(needs more time), it become another fleet(fleet++)
so
cal time for each car position(from end)
end to start poistion, if end-1 car's T > end car's T, fleet++
*/jTreeMap
by class, and and sort desc
Previous791. Custom Sort String, 1122. Relative Sort ArrayNext1877. Minimize Maximum Pair Sum in Array
Last updated
Was this helpful?