Блог пользователя shubhamkumar68

Автор shubhamkumar68, история, 4 года назад, По-английски

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

  • Проголосовать: нравится
  • -2
  • Проголосовать: не нравится

»
4 года назад, # |
  Проголосовать: нравится +4 Проголосовать: не нравится

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 года назад, # |
  Проголосовать: нравится +3 Проголосовать: не нравится

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 года назад, # |
Rev. 2   Проголосовать: нравится 0 Проголосовать: не нравится

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();