線上OJ:
【06NOIP普及組】明明的隨機數
核心思想:
本題的要求是
1、去重
2、排序
以上兩個要求正好可以使用 set 來實現。set 自帶了去重和排序的功能。輸出時使用 iterator 即可。
解法一、set
#include <bits/stdc++.h>
using namespace std;int n, x;
set<int> s;int main()
{scanf("%d", &n);while(n--){scanf("%d", &x);s.insert(x);}set<int>::iterator it; // 定義指向set的迭代器printf("%d\n", s.size());for(it = s.begin(); it != s.end(); it++) printf("%d ", *it); // 輸出set中每一個數return 0;
}
解法二、 sort + unique
我們可以利用sort + unique來完成。
unique是STL函數,包含于 <algorithm> 頭文件中。功能是將數組中相鄰的重復元素去除。然而其 本質 是 將重復的元素移動到數組的末尾,最后再 將迭代器指向第一個重復元素的下標。
所以,如果利用unique實現去重的功能,需要注意
1、先排序。因為unique只對相鄰的重復元素有效;
2、unique并未刪除重復元素,只是將重復元素 移動到 數組的 末尾;
3、unique返回的是指向末尾第一個重復元素的迭代器
4、基于第2點和第3點,如果需要知道數組中不重復元素的個數,需要用unique返回的迭代器減去數組的起始地址,即
l e n = u n i q u e ( a , a + n ) ? a ; len = unique(a, a+n) - a; len=unique(a,a+n)?a;
#include <bits/stdc++.h>
using namespace std;int n;int main()
{scanf("%d", &n);int a[n];for(int i = 0; i < n; i++) scanf("%d", &a[i]); // 讀入sort(a, a+n); // 先排序int len = unique(a, a+n) - a; // 去重,并計算不重復元素的個數printf("%d\n", len); // 輸出長度for(int i = 0; i < len; i++) printf("%d ", a[i]); // 輸出不重復的元素return 0;
}