-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDistinctInArray
More file actions
45 lines (30 loc) · 1.12 KB
/
DistinctInArray
File metadata and controls
45 lines (30 loc) · 1.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
Write a function
function solution($A);
that, 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.
Write an efficient algorithm for the following assumptions:
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].
******************************************* SOLUTION ********************************************
function solution($A)
{
$length = count($A);
if ($length < 0 || $length > 100000) {
return 0;
}
$distinctArray = [];
for ($i = 0; $i < $length; $i++) {
if ($A[$i] < -abs(1000000) || $A[$i] > 1000000) {
return 0;
break;
}
if (isset($distinctArray[$A[$i]])) {
$distinctArray[$A[$i]] += 1;
}
$distinctArray[$A[$i]] = 1;
}
return count($distinctArray);
}