第一个是错误的,我试图使用数学方法进行解决,但是忘了考虑当追上之后速度变慢的情况。如果有时间的话我会把这个进行完善,但是我直接采用官方的解题方法。
class Solution {
public int carFleet(int target, int[] position, int[] speed) {
//怎么判断能追上?
//用( target - position )/ speed算出时间,如果时间小,并且初始路程远,则将其计数
int len = position.length;
//边界处理
if (len < 2) return len;
int time [] = new int[len];
int number = 0;
//将其排序
Arrays.sort(position);
for (int i = 0; i < len; i++) {
int temp = target - position[i];
// System.out.println(Math.ceil((double) temp / speed[i]));
time[i] = (int)Math.ceil((double) temp / speed[i]);
}
//再进行遍历,判断时间和路程的比较
for (int i = 0; i < len; i++){
for (int j = 0; j < len; j++){
//要跳过当 i = j的情况
if (i == j) continue;
//如果时间小,并且初始路程远,则将其计数
if (time[i] <= time[j] && position[i] >= position[j]) {
number++;
break;
}
}
}
return number;
}
}
官方的解题方法
思路:
class Solution {
public int carFleet(int target, int[] position, int[] speed) {
int N = position.length;
Car[] cars = new Car[N];
for (int i = 0; i < N; ++i)
cars[i] = new Car(position[i], (double) (target - position[i]) / speed[i]);
Arrays.sort(cars, (a, b) -> Integer.compare(a.position, b.position));
int ans = 0, t = N;
while (--t > 0) {
if (cars[t].time < cars[t-1].time) ans++; //if cars[t] arrives sooner, it can't be caught
else cars[t-1] = cars[t]; //else, cars[t-1] arrives at same time as cars[t]
}
return ans + (t == 0 ? 1 : 0); //lone car is fleet (if it exists)
}
}
class Car {
int position;
double time;
Car(int p, double t) {
position = p;
time = t;
}
}