Distinct numbers
You are given a list of N integers, and your task is to calculate the number of distinct values in the list.
Input
The first input line has an integer n: the number of values.
The second line has the integers x1,x2,…,xn.
Output
Print one integer: the number of distinct values.
Constraints
1≤n≤2⋅
1≤xi≤1091
Example
Input:
5
2 3 2 2 3
Output:
2
To solve this problem, all we have to do is to just count distinct values which can be done using a set data structure.
A set can be used to solve this problem, which stores the distinct values.
#include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cin >> n;
vector<int>v(n);
for(int i=0;i<n;i++)cin >> v[i];
set<int>st;
for(auto it: v)st.insert(it);
cout << st.size();
}
That was the first approach, let's see another approach to solve this problem.
The second approach is to use a hashmap to count the number of distinct values.
#include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cin >> n;
map<int,int>mp;
for(int i=0;i<n;i++){
int x;
cin >> x;
mp[x]++;
}
cout << mp.size();
}
That's all for this blog, will see you in the next one soon.