Compute number of distinct values in an array
ℹ️ © Codility, 2009-2018
Problem
Write a function that, given an array A consisting of n integers, returns the number of distinct values in array A.
Assume that:
• n is an integer within the range [0 … 100,000];
• each element of array A is an integer within the range [-1,000,000 … 1,000,000].
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.
Complexity:
• expected worst-case time complexity is O(n · log(n));
• expected worst-case space complexity is O(n) (not counting the storage required for input arguments).
Solution
C#
using System; class Solution { public int solution(int[] A) { int r = 0; int n = A.Length; if (n > 0) { r++; Array.Sort(A); for (int i = 1; i < n; i++) { if (A[i] != A[i - 1]) { r++; } } } return r; } }
Java
import java.util.Arrays; class Solution { public int solution(int[] A) { int r = 0; int n = A.length; if (n > 0) { r++; Arrays.sort(A); for (int i = 1; i < n; i++) { if (A[i] != A[i - 1]) { r++; } } } return r; } }
JavaScript
function solution(A) { let r = 0; let n = A.length; if (n > 0) { r++; A.sort((a, b) => a - b); for (let i = 1; i < n; i++) { if (A[i] != A[i - 1]) { r++; } } } return r; }
PHP
function solution($A) { $r = 0; $n = count($A); if ($n > 0) { $r++; sort($A); for ($i = 1; $i < $n; $i++) { if ($A[$i] != $A[$i - 1]) { $r++; } } } return $r; }