离散化之“排序+去重”经典代码 ← vector实现

【算法分析】
★ 离散化的本质,是
映射。原理是将间隔很大的元素,映射到相邻的位置上,从而减少对空间的需求,也减少计算量。

//sort & de-weight for vector
vector<int> v;
sort(v.begin(),v.end());
v.erase(unique(v.begin(),v.end()), v.end());

★ for(auto iter:vec) 及 for(auto &iter:vec) 的典型用法
https://blog.csdn.net/hnjzsyjyj/article/details/132118215


【算法代码】

#include <bits/stdc++.h>
using namespace std;

vector<int> v;
int n,x;

int main() {
    cin>>n;
    while(n--) {
        cin>>x;
        v.push_back(x);
    }

    //sort & de-weight for vector
    sort(v.begin(),v.end());
    v.erase(unique(v.begin(),v.end()), v.end());

    for(auto i:v) {
        cout<<i<<" ";
    }

    return 0;
}

/*
in:
8
3 7 1 8 9 3 1 1

out:
1 3 7 8 9
*/




 

猜你喜欢

转载自blog.csdn.net/hnjzsyjyj/article/details/143315085