Version #2 HashMap
62.06 %
class Solution {
public int carFleet(int target, int[] position, int[] speed) {
if (position == null || position.length == 0 || speed == null || speed.length == 0 || position.length != speed.length) {
return 0;
}
Map<Integer, Double> time = new HashMap<>();
for (int i = 0; i < position.length; i++) {
time.put(position[i], 1.0 * (target - position[i]) / speed[i]);
}
Arrays.sort(position);
int fleet = 1;
double currTime = time.get(position[position.length - 1]);
double prevTime = currTime;
for (int i = position.length - 2; i >= 0; i--) {
currTime = time.get(position[i]);
if (currTime > prevTime) {
prevTime = currTime;
fleet++;
}
}
return fleet;
}
}
Version #1 TreeMap
一刷
class Solution {
public int carFleet(int target, int[] position, int[] speed) {
TreeMap<Integer, Double> map = new TreeMap<>(Collections.reverseOrder());
for (int i = 0; i < position.length; i++) {
double time = (target - position[i]) / (double) speed[i];
map.put(position[i], time);
}
int fleet = 0;
double slowest = 0;
// key -> position, value -> time
for (double currTime : map.values()) {
if (currTime > slowest) {
fleet++;
slowest = currTime;
}
}
return fleet;
}
}
No comments:
Post a Comment