LeetCode -. 853 fleet

N car is located towards the common destination target of miles away along a lane.

Each vehicle i speed [i] (miles / hour) at a constant speed, from an initial position towards a destination position [i] (mi) along the lane.

A car will never be more than another car in front, but it can catch up to, and the vehicle in front followed by travel at the same speed.

At this point, we will ignore the distance between the two vehicles, that is to say, they are assumed to be in the same position.

Some non-empty by the team is traveling in the same position, with the same vehicle speed thereof. Note that a car can be a team.

Even a car at a destination only caught up with the team, they will still be regarded as one and the same team.

How many teams to reach the destination?

示例:

输入:target = 12, position = [10,8,0,5,3], speed = [2,4,1,1,3]
输出:3
解释:
从 10 和 8 开始的车会组成一个车队,它们在 12 处相遇。
从 0 处开始的车无法追上其它车,所以它自己就是一个车队。
从 5 和 3 开始的车会组成一个车队,它们在 6 处相遇。
请注意,在到达目的地之前没有其它车会遇到这些车队,所以答案是 3。
提示:
    0 <= N <= 10 ^ 4
    0 < target <= 10 ^ 6
    0 < speed[i] <= 10 ^ 6
    0 <= position[i] < target
    所有车的初始位置各不相同。

Source: stay button (LeetCode)
link: https://leetcode-cn.com/problems/car-fleet

One

This question is said to have a range of vehicles on the road, the car in a different location, and each has a different speed, but the direction of travel are the same. If the rear of the car to catch up with the front of the car before it reaches the end, it will be like as GEEK followed thereafter, and the speed dropped and the car in front of the same, can be seen as a team, of course, a separate cars can be seen as a team, we asked how many convoys to reach the terminal. This question is a feeling word problems in primary school, and what the dog chasing people ah, people chase the dogs and the like. This question is in fact the correct solution is not easy to think of the idea, because it is easy to have focused their attention to each vehicle, each time to calculate the position where, as well as the location of the encounter with the car in front, which is actually the This question is complicated think, in fact, does not need to know the location of the car meet, only care about whether the composition of the team together through the finish line, then how can we know whether together over the line on the road, the easiest way is to look at the time, if car B a behind the car, and the car B is less than or equal to the time of the finish line car a, then car a and B must know will form over the line with the team. In this case, can be from the end nearest the car starts, the first line is calculated which collision time, and then again traversed the car behind, if the back of the car collision timeline less time in front of the vehicle, the composition will team. On the other hand, if more than the car in front of time, then could not catch up with the car in front, so that they will form a new team, and is a front, the result is increased from 1 to res.

With ideas, we can achieve a specific, use a TreeMap to establish the position of the car and it reaches a mapping between the end of time, this time using a double type, minus the current position by the end position, and dividing by the speed to get. We want to position the car from the big start processing, and TreeMap is the small figure standing in the front, where the use of a small trick, is to use when mapping is to position the negative, so that we can first deal with a large car original position so that the correct statistics of the number of teams, see the following code:

Solution one:

class Solution {
public:
    int carFleet(int target, vector<int>& position, vector<int>& speed) {
        int res = 0; double cur = 0;
        map<int, double> pos2time;
        for (int i = 0; i < position.size(); ++i) {
            pos2time[-position[i]] = (double)(target - position[i]) / speed[i];
        }
        for (auto a : pos2time) {
            if (a.second <= cur) continue;
            cur = a.second;
            ++res;
        }
        return res;
    }
};

We can also use the priority queue to do, because it is automatically arranged in descending order, so do not use the above small trick. Another point of difference is above, not on the time line calculated at the beginning, but direct deposit is speed, because certainly higher than the deposit integer memory to save space double type. When after the treatment, and then remove the position and velocity computation time, and then the same with the above operation can, see the following code:

Solution two:

class Solution {
public:
    int carFleet(int target, vector<int>& position, vector<int>& speed) {
        int res = 0; double cur = 0;
        priority_queue<pair<int, int>> q;
        for (int i = 0; i < position.size(); ++i) {
            q.push({position[i], speed[i]});
        }   
        while (!q.empty()) {
            auto t = q.top(); q.pop();
            double timeNeeded = (double)(target - t.first) / t.second;
            if (timeNeeded <= cur) continue;
            cur = timeNeeded;
            ++res;
        }
        return res;
    }
};

two

Method One: Sort

analysis

We first of these vehicles in descending order according to their starting position, and with (target - position) / speed of each vehicle is calculated when the vehicle is not affected by the remaining traveling time to the desired end point. For two cars neighboring S and F, F is greater than the start position S, if S with the end of the time required less F, the F S will catch up before the end and form a vehicle. This is because before the catch F, S and the traveling speed is not reduced and F because there may be caught up on the vehicle speed decreases, the S can always catch the front end F.

algorithm

After the starting position of the vehicle in accordance with the descending order, these vehicles we sequential scanning. If two cars adjacent to the former than the latter short time needed to travel to the end, then the latter will never catch up with the former, that a number of vehicles from the beginning of the latter will form a new team; if the former than the latter with a short time to the desired end point, the latter can catch up before the end of the former, and the former and form a vehicle. At this time we will reach the end of the latter set time to reach the end of the former.

Java

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++;
            else cars[t-1] = cars[t];
        }

        return ans + (t == 0 ? 1 : 0); 
    }
}

class Car {
    int position;
    double time;
    Car(int p, double t) {
        position = p;
        time = t;
    }
}

Python

class Solution(object):
    def carFleet(self, target, position, speed):
        cars = sorted(zip(position, speed))
        times = [float(target - p) / s for p, s in cars]
        ans = 0
        while len(times) > 1:
            lead = times.pop()
            if lead < times[-1]: ans += 1 
            else: times[-1] = lead 

        return ans + bool(times)

Complexity Analysis

Time complexity: O (NlogN), is the time complexity of sorting.

Complexity Space: O (N), the time the vehicle reaches the end of memory required.

Guess you like

Origin www.cnblogs.com/wwj99/p/12294068.html