MajorityElement   A
last analyzed

Complexity

Total Complexity 12

Size/Duplication

Total Lines 43
Duplicated Lines 0 %

Importance

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

3 Methods

Rating   Name   Duplication   Size   Complexity  
A majorityElement2() 0 14 5
A majorityElement3() 0 8 2
A majorityElement() 0 15 5
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
class MajorityElement
8
{
9
    public static function majorityElement(array $nums): int
10
    {
11
        [$res, $map, $cnt] = [0, [], count($nums)];
12
        if (empty($nums)) {
13
            return $res;
14
        }
15
        foreach ($nums as $num) {
16
            $map[$num] = isset($map[$num]) ? ++$map[$num] : 1;
17
            if ($map[$num] > $cnt / 2) {
18
                $res = $num;
19
                break;
20
            }
21
        }
22
23
        return $res;
24
    }
25
26
    public static function majorityElement2(array $nums): int
27
    {
28
        [$res, $cnt] = [0, 0];
29
        if (empty($nums)) {
30
            return $res;
31
        }
32
        foreach ($nums as $num) {
33
            if ($cnt === 0) {
34
                $res = $num;
35
            }
36
            $res === $num ? $cnt++ : $cnt--;
37
        }
38
39
        return $res;
40
    }
41
42
    public static function majorityElement3(array $nums): int
43
    {
44
        if (empty($nums)) {
45
            return 0;
46
        }
47
        sort($nums);
48
49
        return $nums[floor(count($nums) / 2)];
50
    }
51
}
52