Car Fleet

Intuition

The problem involves cars moving towards a destination along a one-lane road, and the task is to determine the number of car fleets that will arrive at the destination. A car fleet is a set of cars driving at the same position and speed, and a car can never pass another car but can catch up to it and drive bumper to bumper.

Approach

The provided solution uses a stack to keep track of the time it takes for each car to reach the destination. The main idea is to sort the cars based on their starting positions in descending order and calculate the time it takes for each car to reach the destination. If a car catches up to another car before the destination, they form a fleet.

Create pairs of (position, speed) for each car.
Sort the pairs in descending order based on the starting positions.
Iterate through the sorted pairs, calculate the time it takes for each car to reach the destination, and push it onto the stack.
If the current car catches up to the car in front of it (the time for the current car is less than or equal to the time for the car in front), pop the stack to merge the fleets.
The length of the final stack represents the number of car fleets that will arrive at the destination.

Complexity

  • Time complexity:

The time complexity of this solution is O(n log n), where n is the number of cars. The dominant factor is the sorting step.

  • Space complexity:

The space complexity is O(n) due to the stack storing the time for each car to reach the destination.

Code

class Solution:
    def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:
        pair = [[p,s] for p,s in zip(position,speed)]
        stack=[]
        pair = sorted(pair)[::-1]
        for p,s in pair:
            stack.append((target-p)/s)
            if len(stack) >= 2 and stack[-1] <= stack[-2]:
                stack.pop()
        return len(stack)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值