imajinyun /
leetcode-php
| 1 | <?php |
||
| 2 | |||
| 3 | declare(strict_types=1); |
||
| 4 | |||
| 5 | namespace leetcode; |
||
| 6 | |||
| 7 | class NextGreaterElementII |
||
| 8 | { |
||
| 9 | public static function nextGreaterElements(array $nums): array |
||
| 10 | { |
||
| 11 | if (empty($nums)) { |
||
| 12 | return []; |
||
| 13 | } |
||
| 14 | $n = count($nums); |
||
| 15 | [$ans, $stack] = [array_fill(0, $n, -1), []]; |
||
| 16 | for ($i = 0; $i < $n * 2; $i++) { |
||
| 17 | $k = $i % $n; |
||
| 18 | while ($stack && $nums[end($stack)] < $nums[$k]) { |
||
|
0 ignored issues
–
show
|
|||
| 19 | $ans[array_pop($stack)] = $nums[$k]; |
||
| 20 | } |
||
| 21 | array_push($stack, $k); |
||
| 22 | } |
||
| 23 | |||
| 24 | return $ans; |
||
| 25 | } |
||
| 26 | |||
| 27 | public static function nextGreaterElements2(array $nums): array |
||
| 28 | { |
||
| 29 | if (empty($nums)) { |
||
| 30 | return []; |
||
| 31 | } |
||
| 32 | $n = count($nums); |
||
| 33 | [$ans, $stack] = [array_fill(0, $n, -1), []]; |
||
| 34 | for ($i = 0; $i < $n; $i++) { |
||
| 35 | while ($stack && $nums[end($stack)] < $nums[$i]) { |
||
|
0 ignored issues
–
show
The expression
$stack of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.
This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent. Consider making the comparison explicit by using Loading history...
|
|||
| 36 | $ans[array_pop($stack)] = $nums[$i]; |
||
| 37 | } |
||
| 38 | array_push($stack, $i); |
||
| 39 | } |
||
| 40 | |||
| 41 | for ($i = 0; $i < $n; $i++) { |
||
| 42 | while ($stack && $nums[end($stack)] < $nums[$i]) { |
||
| 43 | $ans[array_pop($stack)] = $nums[$i]; |
||
| 44 | } |
||
| 45 | if (empty($stack)) { |
||
| 46 | break; |
||
| 47 | } |
||
| 48 | } |
||
| 49 | |||
| 50 | return $ans; |
||
| 51 | } |
||
| 52 | } |
||
| 53 |
This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.
Consider making the comparison explicit by using
empty(..)or! empty(...)instead.