【优化策略】离散化

概念

离散化是算法设计中处理大数据范围时的关键技巧,它将大范围的数据映射到有较小的的离散空间中,同时保持数据的相对关系。

本质:将原始数据映射到紧凑的连续整数空间

数学表示:建立映射函数 f: ℝ → ℤ,满足 x < y ⇒ f(x) < f(y)

典型场景:

坐标范围极大但数据点稀疏(1e9范围仅1e5个点)

需要构建线段树/树状数组但值域过大

数据值本身无意义而只需保留相对大小关系

实现

cpp 复制代码
//方式一:排序 + 去重 + 二分查找(在disc中依次查找a的每个元素,返回在disc中的下标) 
#include <iostream>
#include <algorithm>
using namespace std; 
const int N = 1e5 + 10;
int a[N],n;
int disc[N],pos;

//二分找x,返回下标 
int binary_search(int x)
{
	int left = 1,right = pos;	
	while(left < right)
	{
		int mid = (left + right) / 2;
		if(disc[mid] >= x) right = mid;
		else left = mid + 1;`
	}
	return left
}

int main() 
{
	cin >> n;
	for(int i=1;i<=n;i++) 
	{
		cin >> a[i];
		disc[++pos] = a[i]; //pos在这里起到枚举下标的作用 
	}
	sort(disc+1,disc+pos+1); //默认排升序
	pos = unique(disc+1,disc+pos+1) - (disc+1); //给元素去重 pos在这里接收去重后元素的个数 
	for(int i=1;i<=n;i++)
	{	
		printf("%d离散化后的值为%d\n",a[i],binary_search(a[i]));
	} 
	
	return 0;
}
cpp 复制代码
//方式二:排序 + 哈希表去重并且记录离散化后的值 
#include <iostream>
#include <algorithm>
#include <unordered_map>
using namespace std; 
const int N = 1e5 + 10;
int a[N],n;
int disc[N],pos;
unordered_map<int,int> mp;

int main() 
{
	cin >> n;
	for(int i=1;i<=n;i++) 
	{
		cin >> a[i];
		disc[++pos] = a[i]; 
	}
	sort(disc+1,disc+pos+1); //默认排升序
	int cnt = 0;
	for(int i=1;i<=pos;i++)
	{
		int x = disc[i];
		if(mp.count(x)) continue;
		mp[x] = ++cnt; //哈希表中储存的是 disc中的各个元素 及其 从小到大分别是第几号 
	}
	for(int i=1;i<=n;i++)
	{	
		printf("%d离散化后的值为%d\n",a[i],mp[a[i]]);
	} 
	
	return 0;
}
相关推荐
闻缺陷则喜何志丹1 个月前
【二分查找 树状数组 差分数组 离散化 】P6172 [USACO16FEB] Load Balancing P|省选-
c++·算法·二分查找·洛谷·离散化·差分数组·数组数组
青云交5 个月前
大数据新视界 -- 大数据大厂之 Hive 数据安全:权限管理体系的深度解读(上)(15/ 30)
大数据·数据一致性·未来趋势·优化策略·hive 集成·大数据工具·集成模式
青云交6 个月前
大数据新视界 -- Impala 性能优化:分布式环境中的优化新视野(下)(28 / 30)
大数据·性能优化·资源管理·impala·优化策略·分布式环境·数据布局
青云交7 个月前
大数据新视界 --大数据大厂之 Hadoop MapReduce 优化指南:释放数据潜能,引领科技浪潮
大数据·性能调优·数据压缩·代码示例·hadoopmapreduce·优化策略·技术融合
buaichifanqie7 个月前
离散化算法
c++·算法·离散化
边疆.9 个月前
基础算法:离散化(C++实现)
开发语言·c++·算法·stl·离散化
无名之逆1 年前
3072. 将元素分配到两个数组中 II Rust 线段树 + 离散化
开发语言·算法·rust·线段树·二分·树状数组·离散化
Wy. Lsy1 年前
小红统计区间(hard) - 树状数组 + 离散化
c++·算法·树状数组·离散化
gz=zg1 年前
【算法】离散化 与 哈希 之间的区别
算法·哈希算法·离散化