[編程題]隨機數的去重與排序

題目描述
明明想在學校中請一些同學一起做一項問卷調查,爲了實驗的客觀性,他先用計算機生成了N個1到1000之間的隨機整數(N≤1000),對於其中重複的數字,只保留一個,把其餘相同的數去掉,不同的數對應着不同的學生的學號。然後再把這些數從小到大排序,按照排好的順序去找同學做調查。請你協助明明完成“去重”與“排序”的工作。

我的思路與解答:

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
    int n;
    while(cin>>n)
    {
    vector<int> inputArry(n);
    for(int i=0;i<n;++i)
    {
        cin>>inputArry[i];
    }
    sort(inputArry.begin(),inputArry.end());
    vector<int>::iterator pos;
    pos=unique(inputArry.begin(),inputArry.end());
    inputArry.erase(pos,inputArry.end());
    vector<int>::iterator it;
    for(it=inputArry.begin();it!=inputArry.end();++it)
    {
        cout<<*it<<'\n';
    }
    }
    return 0;
}

主要需要注意的有:
1.vector<int> inputArry(n); 如果下面採用遍歷的方式進行賦值,一定記得定義數組的時候要給定數組大小;如果採用push_back()來初始化,則不需要;
2.對sort,unique的使用,包含頭文件algorithm,unique是將重複的字符放在最後,並且返回第一個重複的字符的位置;可以使用erase將這個位置到末尾的字符全部刪除;

在牛客上看到一個牛人寫的答案,感覺思路的確很厲害,引用一下。

#include <iostream>
using namespace std;
int main() {
    int N, n;
    while (cin >> N) {
        int a[1001] = { 0 };
        while (N--) {
            cin >> n;
            a[n] = 1;
        }
        for (int i = 0; i < 1001; i++)
            if (a[i])
                cout << i << endl;
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章