LargestUniqueNumber   A
last analyzed

Complexity

Total Complexity 15

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 15
eloc 29
c 1
b 0
f 0
dl 0
loc 47
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
B largestUniqueNumber() 0 21 8
B largestUniqueNumber2() 0 22 7
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
class LargestUniqueNumber
8
{
9
    public static function largestUniqueNumber(array $nums): int
10
    {
11
        if (empty($nums)) {
12
            return -1;
13
        }
14
        $n = count($nums);
15
        if ($n === 1) {
16
            return $nums[0];
17
        }
18
        sort($nums);
19
        if ($nums[$n - 1] !== $nums[$n - 2]) {
20
            return $nums[$n - 1];
21
        }
22
        for ($i = $n - 2; $i > 0; $i--) {
23
            [$prev, $curr, $next] = [$nums[$i - 1], $nums[$i], $nums[$i + 1]];
24
            if ($prev !== $curr && $curr !== $next) {
25
                return $curr;
26
            }
27
        }
28
29
        return $nums[0] !== $nums[1] ? $nums[0] : -1;
30
    }
31
32
    public static function largestUniqueNumber2(array $nums): int
33
    {
34
        if (empty($nums)) {
35
            return -1;
36
        }
37
        $n = count($nums);
0 ignored issues
show
Unused Code introduced by
The assignment to $n is dead and can be removed.
Loading history...
38
        [$map, $max, $min] = [[], -1, 1001];
39
        foreach ($nums as $num) {
40
            $map[$num] = ($map[$num] ?? 0) + 1;
41
            $max = $max > $num ? $max : $num;
42
            $min = $min < $num ? $min : $num;
43
        }
44
        [$ans, $tmp] = [-1, $max];
45
        while ($tmp >= $min) {
46
            if ($map[$tmp] === 1) {
47
                $ans = $tmp;
48
                break;
49
            }
50
            $tmp--;
51
        }
52
53
        return $ans;
54
    }
55
}
56