[LeetCode] 853. Car Fleet 車隊


N cars are going to the same destination along a one lane road.  The destination is target miles away.

Each car i has a constant speed speed[i] (in miles per hour), and initial position position[i] miles towards the target along the road.

A car can never pass another car ahead of it, but it can catch up to it, and drive bumper to bumper at the same speed.

The distance between these two cars is ignored - they are assumed to have the same position.

car fleet is some non-empty set of cars driving at the same position and same speed.  Note that a single car is also a car fleet.

If a car catches up to a car fleet right at the destination point, it will still be considered as one car fleet.


How many car fleets will arrive at the destination?

Example 1:

Input: target = 12, position = [10,8,0,5,3], speed = [2,4,1,1,3] Output: 3 Explanation: The cars starting at 10 and 8 become a fleet, meeting each other at 12. The car starting at 0 doesn't catch up to any other car, so it is a fleet by itself. The cars starting at 5 and 3 become a fleet, meeting each other at 6. Note that no other cars meet these fleets before the destination, so the answer is 3.

Note:

    1. 0 <= N <= 10 ^ 4
    2. 0 < target <= 10 ^ 6
    3. 0 < speed[i] <= 10 ^ 6
    4. 0 <= position[i] < target
    5. All initial positions are different.

N輛車沿着一條車道駛向位於target英里之外的共同目的地。每輛車i以恆定的速度speed[i](英里/小時),從初始位置 position[i](英里)沿車道駛向目的地。
一輛車永遠不會超過前面的另一輛車,但它可以追上去,並與前車以相同的速度緊接着行駛。此時,我們會忽略這兩輛車之間的距離,也就是說,它們被假定處於相同的位置。車隊是一些由行駛在相同位置、具有相同速度的車組成的非空集合。注意,一輛車也可以是一個車隊。即便一輛車在目的地才趕上了一個車隊,它們仍然會被視作是同一個車隊。求會有多少車隊到達目的地?

解法:先把車按照位置進行排序,然后計算出每個車在無阻攔的情況下到達終點的時間,如果后面的車到達終點所用的時間比前面車小,那么說明后車會比前面的車先到,由於后車不能超過前車,所以這種情況下就會合並成一個車隊。用棧來存,對時間進行遍歷,對於那些應該合並的車不進棧就行了,最后返回棧的長度。或者直接用一個變量存最近前車到達時間,用另一變量記錄車隊的數量,如果循環的時間大於記錄的前車時間,則當前的車不會比之前的車先到達,為一個新車隊,更新變量。

Java:

public int carFleet(int target, int[] pos, int[] speed) {
        TreeMap<Integer, Double> m = new TreeMap<>();
        for (int i = 0; i < pos.length; ++i) m.put(-pos[i], (double)(target - pos[i]) / speed[i]);
        int res = 0; double cur = 0;
        for (double time : m.values()) {
            if (time > cur) {
                cur = time;
                res++;
            }
        }
        return res;
    }

Java:

class Solution {
        public int carFleet(int target, int[] position, int[] speed) {
        int N = position.length;
        int res = 0;
        //建立位置-時間的N行2列的二維數組
        double[][] cars = new double[N][2];
        for (int i = 0; i < N; i++) {
            cars[i] = new double[]{position[i], (double) (target - position[i]) / speed[i]};
        }
        Arrays.sort(cars, (a, b) -> Double.compare(a[0], b[0]));
        double cur = 0;

        //從后往前比較
        for (int i = N - 1; i >= 0; i--) {
            if (cars[i][1] > cur) {
                cur = cars[i][1];
                res++;
            }
        }
        return res;
    }

}  

Python:

 def carFleet(self, target, pos, speed):
        time = [float(target - p) / s for p, s in sorted(zip(pos, speed))]
        res = cur = 0
        for t in time[::-1]:
            if t > cur:
                res += 1
                cur = t
        return res

Python:

class Solution:
    def carFleet(self, target, position, speed):
        """
        :type target: int
        :type position: List[int]
        :type speed: List[int]
        :rtype: int
        """
        cars = [(pos, spe) for pos, spe in zip(position, speed)]
        sorted_cars = sorted(cars, reverse=True)
        times = [(target - pos) / spe for pos, spe in sorted_cars]
        stack = []
        for time in times:
            if not stack:
                stack.append(time)
            else:
                if time > stack[-1]:
                    stack.append(time)
        return len(stack)

Python:

# Time:  O(nlogn)
# Space: O(n)
class Solution(object):
    def carFleet(self, target, position, speed):
        """
        :type target: int
        :type position: List[int]
        :type speed: List[int]
        :rtype: int
        """
        times = [float(target-p)/s for p, s in sorted(zip(position, speed))]
        result, curr = 0, 0
        for t in reversed(times):
            if t > curr:
                result += 1
                curr = t
        return result 

C++:

int carFleet(int target, vector<int>& pos, vector<int>& speed) {
        map<int, double> m;
        for (int i = 0; i < pos.size(); i++) m[-pos[i]] = (double)(target - pos[i]) / speed[i];
        int res = 0; double cur = 0;
        for (auto it : m) if (it.second > cur) cur = it.second, res++;
        return res;
    }

  

  

  

 

All LeetCode Questions List 題目匯總

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM