离散化的方法

总结有如下几个步骤:
1.拷贝原数组
2.将拷贝的数组排序
3.利用unique()对拷贝数组去重,并记录不重复元素
4.利用lower_bound()离散化

注:唯一需要注意的是下标究竟从几开始

#include <bits/stdc++.h>
using namespace std;
const int maxn = 10005;
int a[maxn], t[maxn];
int n;
int main() {
    scanf("%d", &n);
    for(int i = 1; i <= n; i++) {
        scanf("%d", &a[i]);
        t[i] = a[i]; //t数组相当于是a数组的拷贝
    }
    sort(t + 1, t + 1 + n);//将t数组排序
    int m = unique(t + 1, t + 1 + n) - t - 1;//去重,m是a数组不重复元素个数
    for(int i = 1; i <= n; i++) {
        a[i] = lower_bound(t + 1, t + 1 + m, a[i]) - t;//下标从1开始
    }
    for(int i=1;i<=n;i++)
    {
     printf("%d ",a[i]);//离散化后的值,不改变相对顺序
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/yiqzq/article/details/79993145