LargestNumberAtLeastTwiceOfOthers::dominantIndex()   B
last analyzed

Complexity

Conditions 7
Paths 10

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 10
c 2
b 0
f 0
dl 0
loc 19
rs 8.8333
cc 7
nc 10
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
class LargestNumberAtLeastTwiceOfOthers
8
{
9
    public static function dominantIndex(array $nums): int
10
    {
11
        if (empty($nums)) {
12
            return 0;
13
        }
14
        [$index, $n] = [0, count($nums)];
15
        for ($i = 0; $i < $n; $i++) {
16
            if ($nums[$i] > $nums[$index]) {
17
                $index = $i;
18
            }
19
        }
20
21
        for ($i = 0; $i < $n; $i++) {
22
            if ($index !== $i && $nums[$index] < 2 * $nums[$i]) {
23
                return -1;
24
            }
25
        }
26
27
        return $index;
28
    }
29
30
    public static function dominantIndex2(array $nums): int
31
    {
32
        if (empty($nums)) {
33
            return 0;
34
        }
35
        $key = $max = $sub = -1;
36
        foreach ($nums as $i => $num) {
37
            if ($num > $max) {
38
                $sub = $max;
39
                $max = $num;
40
                $key = $i;
41
            } elseif ($num > $sub) {
42
                $sub = $num;
43
            }
44
        }
45
46
        return 2 * $sub <= $max ? $key : -1;
47
    }
48
}
49