LCP 08. 剧情触发时间

题目链接 LCP 08. 剧情触发时间
思路 前缀和+二分法
题解链接 python 前缀和+二分法
关键点 预处理:前处理得到各个时刻三种资源的累计值(必为升序数组);查找:二分法查找三种资源需要满足的时刻,取三者最大值即可得到答案
时间复杂度 \(O(n)\)
空间复杂度 \(O(n)\)

代码实现:

class Solution:
    def getTriggerTime(self, increase: List[List[int]], requirements: List[List[int]]) -> List[int]:
        n = len(increase)
        presum = [
            [0] * (n+1) for _ in range(3)
        ]
        for i, (c, r, h) in enumerate(increase):
            presum[0][i+1] = presum[0][i] + c
            presum[1][i+1] = presum[1][i] + r
            presum[2][i+1] = presum[2][i] + h
        
        # found the left-most index `nums[index] >= val`
        def lower_bound(nums, val):
            left, right = -1, n+1
            while left + 1 < right:
                mid = (left+right) // 2
                if nums[mid] < val:
                    left = mid
                else:
                    right = mid
            return right

        m = len(requirements)
        answer = [-1] * m
        for i, (c, r, h) in enumerate(requirements):
            x = lower_bound(presum[0], c)
            y = lower_bound(presum[1], r)
            z = lower_bound(presum[2], h)
            min_index = max(x, y, z)
            if min_index <= n:
                answer[i] = min_index
        return answer
Python-标准库
class Solution:
    def getTriggerTime(self, increase: List[List[int]], requirements: List[List[int]]) -> List[int]:
        n = len(increase)
        presum = [
            [0] * (n+1) for _ in range(3)
        ]
        for i, (c, r, h) in enumerate(increase):
            presum[0][i+1] = presum[0][i] + c
            presum[1][i+1] = presum[1][i] + r
            presum[2][i+1] = presum[2][i] + h
        
        m = len(requirements)
        answer = [-1] * m
        for i, (c, r, h) in enumerate(requirements):
            x = bisect_left(presum[0], c)
            y = bisect_left(presum[1], r)
            z = bisect_left(presum[2], h)
            min_index = max(x, y, z)
            if min_index <= n:
                answer[i] = min_index
        return answer
posted @ 2024-09-10 23:56  WrRan  阅读(7)  评论(0编辑  收藏  举报