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++

*/j

TreeMap

by class, and and sort desc

Last updated