shubhamkumar68's blog

By shubhamkumar68, history, 4 years ago, In English

how to count all distinct elements in an array ???

  • Vote: I like it
  • -2
  • Vote: I do not like it

| Write comment?
»
4 years ago, # |
  Vote: I like it +4 Vote: I do not like it

If you want to erase duplicates from an array, use unique function. The link is given below:

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.

»
4 years ago, # |
  Vote: I like it +3 Vote: I do not like it

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).

»
4 years ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

Not the best way but simple, Let array be arr[n],

set<int> st; 
for(int i=0;i<n;i++) 
    st.insert(arr[i]); 
cout<<st.size();