-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path347.php
52 lines (49 loc) · 1.18 KB
/
347.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<?php
class Solution
{
/**
* @param Integer[] $nums
* @param Integer $k
* @return Integer[]
*/
public function topKFrequent($nums, $k)
{
$record = array_count_values($nums);
$pq = new PQ;
$i = 0;
foreach ($record as $key => $value) {
if ($i >= $k) {
break;
}
$pq->insert($key, $value);
$i++;
unset($record[$key]);
}
$pq->setExtractFlags(PQ::EXTR_BOTH);
if (!empty($record)) {
foreach ($record as $key => $value) {
$top = $pq->top();
if ($value > $top['priority']) {
$pq->extract();
$pq->insert($key, $value);
}
}
}
$res = [];
while ($pq->valid()) {
array_unshift($res, $pq->current()['data']);
$pq->next();
}
return $res;
}
}
class PQ extends \SplPriorityQueue
{
public function compare($priority1, $priority2)
{
if ($priority1 === $priority2) {
return 0;
}
return $priority1 < $priority2 ? 1 : -1;
}
}