差分数组求区间重叠问题+map遍历方式

这篇博客探讨了如何使用哈希表来解决区间累加求最大值的问题。通过建立差分数组并遍历更新,可以有效地计算出在给定区间内活动的最大重叠数。示例代码中展示了一个具体的实现,该实现应用于LeetCode的'我的日历III'问题。
摘要由CSDN通过智能技术生成

建立哈希表map,给定多个区间[start,end],令map[start]++,map[end]--,从最小的点(所有start、end中)从左到右累加,求最大值

map遍历大体分为两种

map<int,int>mp;
for(auto x:mp)  
{
    cout<<x.first;     //键
    cout<<x.second;    //值
}
map<int,int>mp;
for(auto i=mp.begin();i!=mp.end();i++)//注意不要用<,
{
    cout<<i->first;     //键
    cout<<i->second;    //值
}

贴一个练手题目

https://leetcode.cn/problems/my-calendar-iii/ 

class MyCalendarThree {
private:
    map<int,int>mp;          
public:
    MyCalendarThree() {
    }
    
    int book(int start, int end) {
        mp[start]++;mp[end]--;       //差分数组
        int ans=0;
        int sum=0;
        for(auto i=mp.begin();i!=mp.end();i++)
        {
            sum+=i->second;
            ans=max(ans,sum);
        }
        return ans;
    }
};

/**
 * Your MyCalendarThree object will be instantiated and called as such:
 * MyCalendarThree* obj = new MyCalendarThree();
 * int param_1 = obj->book(start,end);
 */

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

装B且挨揍の

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值