leetcode 1870. Minimum Speed to Arrive on Time (minimum speed to arrive on time)

insert image description here

insert image description here

It is necessary to find a speed so that the total time of dist[i] / speed <= hour,
and if the result of the previous dist[i] / speed is a decimal, you must wait until the next integer time to calculate the next one.
The maximum speed will not exceed 10 7.
If there is no speed that meets the conditions, return -1 .

Ideas:

If the result of the previous dist[i] / speed is a decimal, you must wait until the next integer time to calculate the next one.
That is to say, the dist[i]/speed before the last dist[n-1] must take ceil.

The speed will not exceed 10 7 ,
that is, find a speed in the range of 1 ~ 10 7, so that sum( ceil(dist[i]/speed)) (i=0~n-2) + dist[n-1] / speed <= hour.
You can think of binary search .

There is also a special case where -1 can be returned directly. That is, the number of trains n is particularly large (the number of transfers is large), but when the hour is not too large, no calculation is required.
How to judge, when the maximum value of speed is 10 7 , and dist[i] is all the minimum value of 1, that is, when every train arrives with a swish, but still cannot arrive within the hour.
That is to say, the first n-1 trains take n-1 time (even if the first n-1 trains arrive in 1/10 7
time, they have to wait for 1 hour), the last train takes 10 -7 , the total time spent When n-1+10 -7 is still >hour, return -1 directly.

    public int minSpeedOnTime(int[] dist, double hour) {
    
    
        if (dist.length -1 + 1e-7 > hour) {
    
    
            return -1;
        }
        int left = 1;
        int right = 10000001;

        while(left < right) {
    
    
            int mid = left + (right-left) / 2;
            if(cost(dist, mid) <= hour) {
    
    
                right=mid;
            } else {
    
    
                left = mid+1;
            }
        }
        return left == 10000001 ? -1 : left;
    }

    double cost(int[] dist, int speed) {
    
    
        double res = 0;
        int n = dist.length;
        for(int i = 0; i < n-1; i++) {
    
    
            res += (dist[i]+speed-1)/speed; //代替ceil运算,需要dist[i]和speed都是int
        }
        res += (double)dist[n-1]/speed;
        return res;
    }

Guess you like

Origin blog.csdn.net/level_code/article/details/131935587