LeetCode 853. Car Fleet

1AC - Yay! A super cute one : ) Again, simulate & play with it in your mind, and you will get it.

Key: for car[i] at its position, it can only pass the target with the slowest car ahead of it. So the problem becomes, count # of `slowest` cars in the list.

class Solution(object):
    def carFleet(self, target, position, speed):
        """
        :type target: int
        :type position: List[int]
        :type speed: List[int]
        :rtype: int
        """
        if len(position) < 2: return len(position)
        
        # Get a sorted list of (position, time-to-target)
        ts = [(target-v)*1.0/s for (v, s) in zip(position, speed)]
        v = sorted(zip(position, ts))
        
        # Count the number of slowest fleets
        ret, slowest = 0, -1.0
        for (_, t) in reversed(v):
            if t > slowest:
                slowest = t
                ret += 1
        return ret
        

猜你喜欢

转载自www.cnblogs.com/tonix/p/9194820.html
car