LeetCode——853.车队(Java)

第一个是错误的,我试图使用数学方法进行解决,但是忘了考虑当追上之后速度变慢的情况。如果有时间的话我会把这个进行完善,但是我直接采用官方的解题方法

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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值