Codility - Distinct - Sorting - Java  

by ne on 2022-02-16 under Algo/DS/Problems tagged with codility

Hi,
The problem description is in the comments above the solution below.

The problem belongs to Codility, you can try out it yourself on their platform.
 


import java.util.Arrays;

/**
 * given an array A consisting of N integers, returns the number of distinct values in array A.
 *
 * For example, given array A consisting of six elements such that:
 *  A[0] = 2    A[1] = 1    A[2] = 1
 *  A[3] = 2    A[4] = 3    A[5] = 1
 *
 * the function should return 3, because there are 3 distinct values appearing in array A, namely 1, 2 and 3.
 */
public class Distinct {
    public int solution(int[] A) {
        if(A.length <=1) return A.length;
        Arrays.sort(A);
        int count=1;
        for(int i=1;i < A.length;i++){
            if(A[i] != A[i-1]){
                count++;
            }
        }
        return count;
    }
}