一维区间命中计数
问题描述为:多个区间,统计 target 在多少区间内。
e.g. 力扣 6044. 花期内花的数目
给你一个下标从 0 0 0 开始的二维整数数组 f l o w e r s flowers flowers ,其中 f l o w e r s [ i ] = [ s t a r t i , e n d i ] flowers[i] = [starti, endi] flowers[i]=[starti,endi] 表示第 i 朵花的 花期 从 s t a r t i starti starti 到 e n d i endi endi (都包含)。同时给你一个下标从 0 0 0 开始大小为 $ n 的 整 数 数 组 的整数数组 的整数数组 persons , , , persons[i] 是 第 是第 是第 i $ 个人来看花的时间。
请你返回一个大小为 n 的整数数组 answer ,其中 answer[i]是第 i 个人到达时在花期内花的数目 。
方法一
按时间遍历 + 小根堆 + 延迟删除
from typing import *
from heapq import *
class Solution:
def fullBloomFlowers(self, flowers: List[List[int]], persons: List[int]) -> List[int]:
m = len(flowers)
n = len(persons)
res = [0] * n
# 把花期表按照花期开始时间排序
flowers.sort()
flower_idx = 0
q = []
size = 0
for cur, idx in sorted(zip(persons, range(n)), key=lambda x: x[0]):
# 把花期已经结束的弹出堆
while size > 0 and q[0] < cur:
heappop(q)
size -= 1
# 将花期应该在 cur 前(包括 cur)已经开始,否则 cur 时刻此花不可能处于花期
while flower_idx < m and flowers[flower_idx][0] <= cur:
# 花期在 cur 还未结束,若花期在 cur 已经结束,那么就不可能在 cur 以及之后的时刻处于花期
if flowers[flower_idx][1] >= cur:
heappush(q, flowers[flower_idx][1])
size += 1
flower_idx += 1
# print(cur, q)
res[idx] = size
return res
方法二
问题转换:正在开的花的个数 = 已开放的花的个数 - 已凋谢的花的个数
from typing import *
from heapq import *
class Solution:
def fullBloomFlowers(self, flowers: List[List[int]], persons: List[int]) -> List[int]:
m = len(flowers)
n = len(persons)
res = [0] * n
# 分别统计 cur 时刻已经开放的花的数目 open_cnt、已经凋谢的花 close_cnt
open = [x for x, y in flowers]
close = [y for x, y in flowers]
open.sort(), close.sort()
open_cnt = close_cnt = 0
for cur, idx in sorted(zip(persons, range(n)), key=lambda x: x[0]):
while open_cnt < n and open[open_cnt] <= cur:
open_cnt += 1
while close_cnt < n and close[close_cnt] < cur:
close_cnt += 1
res[idx] = open_cnt - close_cnt
return res