classSolution{classCar{privateint position;privateint speed;publicCar(){}publicCar(int position,int speed){this.position = position;this.speed = speed;}publicintgetPosition(){return position;}publicintgetSpeed(){return speed;}}publicintcarFleet(int target,int[] position,int[] speed){int n = position.length;Car[] cars =newCar[n];// 把每部車的資料放進去for(int i =0; i < n;++i){
cars[i]=newCar(position[i], speed[i]);}// 根據位置排序,由小到大Arrays.sort(cars,Comparator.comparingInt(Car::getPosition));int res =0;// 結果// 從後往前for(int i = n -1; i >=0;--i){// 算出當前車輛到達終點的時間,乘1.0是為了int轉doublefinaldoubleT=(target - cars[i].getPosition())*1.0/
cars[i].getSpeed();int j = i -1;// 前車// 如果前車追得上while(j >=0&&((target - cars[j].getPosition())*1.0/
cars[j].getSpeed())<=T){--j;//檢查再前一部車}++res;
i = j +1;// 其實是指到新的車,因為下個循環i會再減一}return res;}}
2025/04/18
下面的解法似乎更直觀
classSolution{publicintcarFleet(int target,int[] position,int[] speed){int n = position.length;// position, speedint[][] pair =newint[position.length][2];for(int i =0; i < n;++i){
pair[i][0]= position[i];
pair[i][1]= speed[i];}// Large to smallArrays.sort(pair,(a, b)->Integer.compare(b[0], a[0]));int fleets =1;double prevTime =1.0*(target - pair[0][0])/ pair[0][1];for(int i =1; i < n;++i){double currTime =1.0*(target - pair[i][0])/ pair[i][1];// Current car will be late, couldn't catch up to the front car// Therefore form a new fleetif(currTime > prevTime){++fleets;
prevTime = currTime;}}return fleets;}}