二叉搜索树--731题我的日程安排表

IMOS-累积和法

概念

imos法是将累积和算法扩展到多次元、高次元的方法

基础IMOS法

最简单的imos法是1次元0次系数的求解思想。如图,有三个俄罗斯方块,悬空的部分会掉下来,求从左到右的高度
image

例题

题目描述:经营一个咖啡厅,咖啡厅的客人在S时刻进店,E时刻进店。求店里最多有多少客人?

**方法一:朴素解法 **

#include <iostream>
#include <algorithm>
using namespace std;
 
#define C 4
#define T 10
// 每个客人的进入时间
int S[C] = { 1, 3, 5, 7 };
// 每个客人的离开时间
int E[C] = { 2, 8, 6, 8 };
// 店里的人数
int table[T];
 
///SubMain//
int main(int argc, char *argv[])
{
	memset(table, 0, sizeof(table));
	for (int i = 0; i < C; i++) 
	{
		// 从时间 S[i] 到 E[i] - 1 店里人数计数加一
		for (int j = S[i]; j < E[i]; j++) 
		{
			table[j]++;
		}
	}
	// 找最大値
	cout << *max_element(table, table + T) << endl;
	system("pause");
	return 0;
}
///End Sub//

时间复杂度为o(CT)

方法二:IMOS法

#include <iostream>
#include <algorithm>
using namespace std;
 
#define C 4
#define T 10
// 每个客人的进入时间
int S[C] = { 1, 3, 5, 7 };
// 每个客人的离开时间
int E[C] = { 2, 8, 6, 8 };
// 店里的人数
int table[T];
 
///SubMain//
int main(int argc, char *argv[])
{
	memset(table, 0, sizeof(table));
	for (int i = 0; i < C; i++) 
	{
		table[S[i]]++;  // 入店+1
		table[E[i]]--;  // 出店-1
	}
	// 累加
	for (int i = 1; i < T; i++) 
	{
		table[i] += table[i - 1];
	}
	// 找最大値
	cout << *max_element(table, table + T) << endl;
	system("pause");
	return 0;
}
///End Sub//

整体思路:等价于使用了微积分的方法,首先对进店和出店的动作进行微分,那么进店为+1,出店为-1。求店内人数相当于求解对时间轴进行积分

LeetCode题目日程安排表

题目

image

解题内容

class MyCalendarTwo {
public:
    MyCalendarTwo() {   
    }

    bool book(int start, int end) {
        can[start]++;
        can[end]--;
        int sum=0;
        for(auto t:can){ 
            sum+=t.second;
            if(sum>2){
                can[start]--;  //主要理解微分与积分的方法,该方法思路简便。但效率不高
                can[end]++;
                return false;   
            }   
        }
        return true;   
    }
private:
    map<int,int> can;
};

/**
 * Your MyCalendarTwo object will be instantiated and called as such:
 * MyCalendarTwo obj = new MyCalendarTwo();
 * bool param_1 = obj.book(start,end);
 */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值