-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathGFG_CountDistinct.cpp
75 lines (62 loc) · 1.36 KB
/
GFG_CountDistinct.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/*
https://practice.geeksforgeeks.org/problems/distinct-absolute-array-elements4529/1
Count distinct elements in an array
*/
#include <iostream>
#include <algorithm>
#include <unordered_set>
using namespace std;
class Solution
{
public:
int countDistinct(int arr[], int n)
{
int res=1, i ,j;
for( i=1; i<n; i++)
{
for( j=0; j<i; j++)
{
if(arr[i]==arr[j])
break;
}
if(j==i)
res++;
}
return res;
}
int countDistinctSorted(int arr[], int n)
{
sort(arr, arr+n);
int res=0, i ,j;
for( i=0; i<n; i++)
{
while(i<n-1 && arr[i]==arr[i+1])
i++;
res++;
}
return res;
}
int countDistinctUnorderedSet(int arr[], int n)
{
unordered_set<int> s;
int res=0, i ,j;
for( i=0; i<n; i++)
{
if(s.find(arr[i]) == s.end())
{
s.insert(arr[i]);
res++;
}
}
return res;
}
};
// Driver program to test above function
int main()
{
Solution ob;
int arr[] = { 12, 10, 9, 45, 2, 10, 10, 45 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << ob.countDistinct(arr, n);
return 0;
}