跳到正文

算法·理论

离散化

luckydrawbox约 1 分钟
原文
文章信息与版本

文章信息

发布
2021年8月28日
收录
2025年12月12日
更新
2026年11月21日
篇幅
约 1 分钟

版本

  1. v1当前

把长度为 nn 的 aa 数组映射成只有 1∼tot1\sim tot 的整数的 bb 数组,其中返回值 tottot 是 aa 中元素个数。

C++
int discrete(int n,int *a){
    int b[N];
    for(int i=1;i<=n;i++)
        b[i]=a[i];
    sort(b+1,b+n+1);
    int tot=unique(b+1,b+n+1)-(b+1);
    for(int i=1;i<=n;i++)
        a[i]=lower_bound(b+1,b+tot+1,a[i])-b;
    return tot;
}

空间复杂度 O(n)O(n),时间复杂度 O(nlog⁡n)O(n\log n)。

back

原文