• LeetCode每日一题:2251. 花期内花的数目(2023.9.28 C++)


    目录

    2251. 花期内花的数目

    题目描述:

    实现代码与解析:

    离散化差分

    原理思路:


    2251. 花期内花的数目

    题目描述:

            给你一个下标从 0 开始的二维整数数组 flowers ,其中 flowers[i] = [starti, endi] 表示第 i 朵花的 花期 从 starti 到 endi (都 包含)。同时给你一个下标从 0 开始大小为 n 的整数数组 people ,people[i] 是第 i 个人来看花的时间。

    请你返回一个大小为 n 的整数数组 answer ,其中 answer[i]是第 i 个人到达时在花期内花的 数目 。

    示例 1:

    输入:flowers = [[1,6],[3,7],[9,12],[4,13]], people = [2,3,7,11]
    输出:[1,2,2,2]
    解释:上图展示了每朵花的花期时间,和每个人的到达时间。
    对每个人,我们返回他们到达时在花期内花的数目。
    

    示例 2:

    输入:flowers = [[1,10],[3,3]], people = [3,3,2]
    输出:[2,2,1]
    解释:上图展示了每朵花的花期时间,和每个人的到达时间。
    对每个人,我们返回他们到达时在花期内花的数目。
    

    提示:

    • 1 <= flowers.length <= 5 * 104
    • flowers[i].length == 2
    • 1 <= starti <= endi <= 109
    • 1 <= people.length <= 5 * 104
    • 1 <= people[i] <= 109

    实现代码与解析:

    离散化差分

    1. class Solution {
    2. public:
    3. vector<int> fullBloomFlowers(vectorint>>& flowers, vector<int>& people) {
    4. map<int, int> diff; // 差分
    5. for (auto &t: flowers) { // 计算差分
    6. diff[t[0]]++;
    7. diff[t[1] + 1]--;
    8. }
    9. vector<int> pidx(people.size());
    10. for (int i = 0; i < pidx.size(); i++) // 记录下标
    11. pidx[i] = i;
    12. sort(pidx.begin(), pidx.end(), [&](int a, int b) { // 用 & 别用 = 会超时
    13. return people[a] < people[b]; // 根据到达时间对于下标排序
    14. });
    15. vector<int> res(people.size());
    16. int cur = 0;
    17. auto it = diff.begin(); // iter
    18. for (int t: pidx) {
    19. while (it != diff.end() && it->first <= people[t]) {
    20. cur += it->second;
    21. it++;
    22. }
    23. res[t] = cur;
    24. }
    25. return res;
    26. }
    27. };

    原理思路:

            根据题目,差分一定是最先想到的,但是数据量比较大,我们也没必要每个时间的数量都查询到,只需要查询有人去的时间的结果。

            所以,这里用map来代替数组,由于结果要按查询顺序返回,我们记录people下标并且按到达时间排序,为了后面按顺序求前缀和,这样求前缀时,就不用每次都返回开头再求。

            然后开始遍历,对于小于等于现在遍历的人的时间,进行前缀和并且记录结果,最终得到结果数组,返回,完成。

  • 相关阅读:
    ABAP Web Service 调用的一个例子
    解决问题:可以用什么方式实现自动化部署
    ssm高校党员信息管理系统
    C++——继承
    【shell】shell指令学习
    108强初赛成果脱颖而出 2022用友成长型企业数智化成果大赛进入复赛
    大师学SwiftUI第18章Part1 - 图片选择器和相机
    nginx测试配置文件的问题
    (附源码)计算机毕业设计SSM酒店入住管理系统
    UI组件库Kendo UI for Vue原生组件中文 - 按钮概述
  • 原文地址:https://blog.csdn.net/Cosmoshhhyyy/article/details/133380205