Test Failed
Push — master ( 26fc0a...b35cc8 )
by Jinyun
02:24
created

TopKFrequentElements::topKFrequent2()   A

Complexity

Conditions 6
Paths 7

Size

Total Lines 21
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 12
c 1
b 0
f 0
dl 0
loc 21
rs 9.2222
cc 6
nc 7
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
class TopKFrequentElements
8
{
9
    public static function topKFrequent(array $nums, int $k): array
10
    {
11
        if (empty($nums) || $k <= 0) {
12
            return [];
13
        }
14
        $map = array_count_values($nums);
15
        arsort($map);
16
17
        $keys = array_keys($map);
18
        if ($k > count($map)) {
19
            return $keys;
20
        }
21
22
        return array_slice($keys, 0, $k);
23
    }
24
25
    public static function topKFrequent2(array $nums, int $k): array
26
    {
27
        if (empty($nums) || $k <= 0) {
28
            return [];
29
        }
30
        $ans = $map = [];
31
        foreach ($nums as $num) {
32
            $map[$num] = ($map[$num] ?? 0) + 1;
33
        }
34
        arsort($map);
35
36
        $keys = array_keys($map);
37
        if ($k > count($map)) {
38
            return $keys;
39
        }
40
41
        for ($i = 0; $i < $k; $i++) {
42
            array_push($ans, array_shift($keys));
43
        }
44
45
        return $ans;
46
    }
47
48
    public static function topKFrequent3(array $nums, int $k): array
49
    {
50
        if (empty($nums) || $k <= 0) {
51
            return [];
52
        }
53
        $ans = $map = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $map is dead and can be removed.
Loading history...
54
        $map = array_count_values($nums);
55
        $heap = new \SplPriorityQueue();
56
        foreach ($map as $key => $val) {
57
            $heap->insert($key, $val);
58
        }
59
        for ($i = 0; $i < $k; $i++) {
60
            array_push($ans, $heap->extract());
61
        }
62
63
        return $ans;
64
    }
65
}
66