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 @   WrRan  阅读(10)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
· 为什么 退出登录 或 修改密码 无法使 token 失效
点击右上角即可分享
微信分享提示