how to count all distinct elements in an array ???
how to count all distinct elements in an array ???
# | User | Rating |
---|---|---|
1 | tourist | 3690 |
2 | jiangly | 3647 |
3 | Benq | 3581 |
4 | orzdevinwang | 3570 |
5 | Geothermal | 3569 |
5 | cnnfls_csy | 3569 |
7 | Radewoosh | 3509 |
8 | ecnerwala | 3486 |
9 | jqdai0815 | 3474 |
10 | gyh20 | 3447 |
# | User | Contrib. |
---|---|---|
1 | maomao90 | 174 |
2 | awoo | 164 |
3 | adamant | 162 |
4 | TheScrasse | 160 |
5 | nor | 158 |
6 | maroonrk | 156 |
7 | -is-this-fft- | 152 |
8 | orz | 146 |
9 | pajenegod | 145 |
9 | SecondThread | 145 |
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],