建立哈希表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);
*/