Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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
        

 

posted on 2018-06-18 11:58  Tonix  阅读(194)  评论(0编辑  收藏  举报