-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathSlidingWindowMaximum.php
More file actions
106 lines (95 loc) · 2.61 KB
/
SlidingWindowMaximum.php
File metadata and controls
106 lines (95 loc) · 2.61 KB
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
<?php
declare(strict_types=1);
namespace leetcode;
class SlidingWindowMaximum
{
/**
* Note: Time Limit Exceeded.
*
* @param array $nums
* @param int $k
*
* @return array
*/
public static function maxSlidingWindow(array $nums, int $k): array
{
if (empty($nums) || $k <= 0) {
return [];
}
$ans = [];
for ($i = $k - 1, $n = count($nums); $i < $n; $i++) {
$max = $nums[$i];
for ($j = 1; $j < $k; $j++) {
if ($nums[$i - $j] > $max) {
$max = $nums[$i - $j];
}
}
$ans[$i - $k + 1] = $max;
}
return $ans;
}
/**
* Note: Time Limit Exceeded.
*
* @param array $nums
* @param int $k
*
* @return array
*/
public static function maxSlidingWindow2(array $nums, int $k): array
{
$ans = [];
if (empty($nums) || $k <= 0) {
return $ans;
}
$queue = [];
for ($i = 0, $n = count($nums); $i < $n; $i++) {
if (!empty($queue) && current($queue) === $i - $k) {
array_shift($queue);
}
while (!empty($queue) && $nums[$queue[count($queue) - 1]] < $nums[$i]) {
array_pop($queue);
}
$queue[] = $i;
if ($i >= $k - 1) {
$ans[] = $nums[current($queue)];
}
}
return $ans;
}
public static function maxSlidingWindow3(array $nums, int $k): array
{
if (empty($nums) || $k <= 0) {
return [];
}
[$ans, $queue] = [[], new \SplMaxHeap()];
foreach ($nums as $i => $num) {
while (!$queue->isEmpty() && $queue->top()[1] <= $i - $k) {
$queue->extract();
}
$queue->insert([$num, $i]);
if ($i >= $k - 1) {
array_push($ans, $queue->top()[0]);
}
}
return $ans;
}
public static function maxSlidingWindow4(array $nums, int $k): array
{
if (empty($nums) || $k <= 0) {
return [];
}
[$ans, $queue] = [[], new \SplPriorityQueue()];
$queue->setExtractFlags($queue::EXTR_BOTH);
foreach ($nums as $i => $num) {
while (!$queue->isEmpty() && $queue->top()['data'][1] <= $i - $k) {
$queue->extract();
}
$queue->insert([$num, $i], $num);
if ($i >= $k - 1) {
array_push($ans, $queue->top()['data'][0]);
}
}
return $ans;
}
}