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
|
function findMaxSlidingWindow($nums, $k): array { $n = count($nums);&& if ($n == 0) { return []; }
$q = []; $res = [];
for ($i = 0; $i < $n; $i++) { while ($q && $nums[$q[count($q) - 1]] < $nums[$i]) { array_pop($q); } $q[] = $i;
if ($i >= $k - 1) { $res[] = $nums[$q[0]]; if ($q[0] === $i - $k + 1) { array_shift($q); } } }
return $res; }
$nums = [2,5,3,4,5,2,6,3,2,4,10,1,2,0]; $res = $this->findMaxSlidingWindow($nums,3); dump(json_encode($res));
|