-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathLargestUniqueNumber.php
55 lines (49 loc) · 1.29 KB
/
LargestUniqueNumber.php
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
46
47
48
49
50
51
52
53
54
55
<?php
declare(strict_types=1);
namespace leetcode;
class LargestUniqueNumber
{
public static function largestUniqueNumber(array $nums): int
{
if (empty($nums)) {
return -1;
}
$n = count($nums);
if ($n === 1) {
return $nums[0];
}
sort($nums);
if ($nums[$n - 1] !== $nums[$n - 2]) {
return $nums[$n - 1];
}
for ($i = $n - 2; $i > 0; $i--) {
[$prev, $curr, $next] = [$nums[$i - 1], $nums[$i], $nums[$i + 1]];
if ($prev !== $curr && $curr !== $next) {
return $curr;
}
}
return $nums[0] !== $nums[1] ? $nums[0] : -1;
}
public static function largestUniqueNumber2(array $nums): int
{
if (empty($nums)) {
return -1;
}
$n = count($nums);
[$map, $max, $min] = [[], -1, 1001];
foreach ($nums as $num) {
$map[$num] = ($map[$num] ?? 0) + 1;
$max = $max > $num ? $max : $num;
$min = $min < $num ? $min : $num;
}
[$ans, $tmp] = [-1, $max];
while ($tmp >= $min) {
if ($map[$tmp] === 1) {
$ans = $tmp;
break;
}
$tmp--;
}
return $ans;
}
}