LCP 08. 劇情觸發時間

WrRan發表於2024-09-10
題目連結 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

相關文章