LargestNumberAtLeastTwiceOfOthers   A
last analyzed

Complexity

Total Complexity 13

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 13
eloc 22
c 2
b 0
f 0
dl 0
loc 40
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
B dominantIndex() 0 19 7
A dominantIndex2() 0 17 6
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