discretization method

The following steps are summarized:
1. Copy the original array
2. Sort the copied array
3. Use unique() to deduplicate the copied array and record the non-repeating elements
4. Use lower_bound() to discretize

Note: The only thing you need to pay attention to is how many times the subscript starts

#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;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324582549&siteId=291194637