一维区间命中计数

一维区间命中计数

问题描述为:多个区间,统计 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值