You are given a list of whole numbers with repeats. Print each different value once, in increasing order.
What to build
Read n and then n numbers into a set<int>. The set drops the repeats and keeps the values sorted. Print its elements separated by spaces.
Requirements
- Remove the repeats
- Print the values in increasing order, separated by single spaces
Input
The first line has n (1 ≤ n ≤ 100,000). The second line has n whole numbers (each from -10⁹ to 10⁹).
Output
The different values in increasing order, on one line.
Constraints
1 ≤ n ≤ 100,000.
Example
Input:
7
40 10 30 10 20 30 10
Output:
10 20 30 40
Why it works
A set keeps each value once and in sorted order, with O(log n) per insert, so the whole job is O(n log n). Iterating over a set visits the values from smallest to largest.
Examples
7 40 10 30 10 20 30 10
10 20 30 40
3 5 5 5
5
Hints
Hint 1
set<int> s; then s.insert(x) for every x.
Hint 2
for (int v : s) cout << v << " "; visits the values in increasing order.
Hint 3
Print a space before every value except the first, or a space after each one: the judge ignores trailing spaces.
Solution
Show one correct solution (try it yourself first)
#include <iostream>
#include <set>
using namespace std;
int main() {
int n;
cin >> n;
set<int> s;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
s.insert(x);
}
for (int v : s) cout << v << " ";
cout << "\n";
return 0;
}
▶ Open this solution in the compiler, then press Visualize to watch it run step by step