0% found this document useful (0 votes)
5 views1 page

Count Distinct Elements in Array

Uploaded by

kbhavana0602
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views1 page

Count Distinct Elements in Array

Uploaded by

kbhavana0602
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

// Java program to count all distinct elements

// in a given array
import [Link];

class GFG {

static int countDistinct(int arr[], int n)


{
// First sort the array so that all
// occurrences become consecutive
[Link](arr);

// Traverse the sorted array


int res = 0;
for (int i = 0; i < n; i++) {

// Move the index ahead while


// there are duplicates
while (i < n - 1 && arr[i] == arr[i + 1]) {
i++;
}
res++;
}
return res;
}

// Driver code
public static void main(String[] args)
{
int arr[] = { 6, 10, 5, 4, 9, 120, 4, 6, 10 };
int n = [Link];
[Link](countDistinct(arr, n));
}
}

// This code is contributed by 29AjayKumar

You might also like