how to count all distinct elements in an array ???
# | User | Rating |
---|---|---|
1 | jiangly | 3977 |
2 | tourist | 3815 |
3 | jqdai0815 | 3682 |
4 | ksun48 | 3614 |
5 | orzdevinwang | 3526 |
6 | ecnerwala | 3514 |
7 | Benq | 3483 |
8 | hos.lyric | 3381 |
9 | gamegame | 3374 |
10 | heuristica | 3358 |
# | User | Contrib. |
---|---|---|
1 | cry | 169 |
2 | -is-this-fft- | 162 |
3 | Um_nik | 161 |
4 | atcoder_official | 160 |
5 | djm03178 | 157 |
5 | Dominater069 | 157 |
7 | adamant | 154 |
8 | luogu_official | 152 |
8 | awoo | 152 |
10 | TheScrasse | 148 |
how to count all distinct elements in an array ???
Name |
---|
If you want to erase duplicates from an array, use unique function. The link is given below:
https://www.geeksforgeeks.org/stdunique-in-cpp/
If you just want to count no. of unique elements, you can sort the array and maintain a count variable that gets incremented only when a[i]!=a[i+1]. Be careful about the last element since a[n] doesn't exist and your code might give out of bound exception.
Or you can simply create a set and insert the elements from the array. Keep in mind that set, in addition to not accepting duplicates, will also keep the elements in sorted order.
As you are using c++ you can do one of the following: https://ideone.com/28Hs5s O(logn) or simply create an array and count non-marked elements and mark every element you count (marked[a[i]]=1).
Not the best way but simple, Let array be arr[n],