imajinyun /
leetcode-php
| 1 | <?php |
||
| 2 | |||
| 3 | declare(strict_types=1); |
||
| 4 | |||
| 5 | namespace leetcode; |
||
| 6 | |||
| 7 | class DailyTemperatures |
||
| 8 | { |
||
| 9 | public static function dailyTemperatures(array $nums): array |
||
| 10 | { |
||
| 11 | if (empty($nums)) { |
||
| 12 | return []; |
||
| 13 | } |
||
| 14 | $n = count($nums); |
||
| 15 | $ans = array_fill(0, $n, 0); |
||
| 16 | for ($i = 0; $i < $n; $i++) { |
||
| 17 | $curr = $nums[$i]; |
||
| 18 | for ($j = $i + 1; $j < $n; $j++) { |
||
| 19 | if ($nums[$j] > $curr) { |
||
| 20 | $ans[$i] = $j - $i; |
||
| 21 | break; |
||
| 22 | } |
||
| 23 | } |
||
| 24 | } |
||
| 25 | |||
| 26 | return $ans; |
||
| 27 | } |
||
| 28 | |||
| 29 | public static function dailyTemperatures2(array $nums): array |
||
| 30 | { |
||
| 31 | if (empty($nums)) { |
||
| 32 | return []; |
||
| 33 | } |
||
| 34 | $n = count($nums); |
||
| 35 | [$ans, $stack] = [array_fill(0, $n, 0), []]; |
||
| 36 | for ($i = 0; $i < $n; $i++) { |
||
| 37 | while ($stack && $nums[end($stack)] < $nums[$i]) { |
||
|
0 ignored issues
–
show
|
|||
| 38 | $k = array_pop($stack); |
||
| 39 | $ans[$k] = $i - $k; |
||
| 40 | } |
||
| 41 | array_push($stack, $i); |
||
| 42 | } |
||
| 43 | |||
| 44 | return $ans; |
||
| 45 | } |
||
| 46 | } |
||
| 47 |
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.