Monday, January 8, 2024

CSES :: Sorting and Searching :: Distinct Numbers

Problem : Please find the problem here.

Explanation : Sort the array and count the number of distinct entries by iterating and checking if the current element of the arrray is equal to immediate previous element.

Code : 

#include <bits/stdc++.h>

using namespace std;

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);

    int n; cin >> n;
    int arr[n];

    for (int i = 0; i < n; i++) {
        cin >> arr[i];
    }

    sort(arr, arr+n);

    int  uniqueCount = 0, prev = -1;
    for (int i = 0; i < n; i++) {
        if (arr[i] != prev) {
            uniqueCount++;
        }
        prev = arr[i];
    }

    cout << uniqueCount;
    return 0;
}

No comments:

Post a Comment