给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。

    image.png

    1. <?php
    2. class Solution {
    3. public function trap($height) {
    4. $stackKey = new SplStack();
    5. $volume = 0;
    6. for ($i = 0; $i < count($height); $i++) {
    7. if ($stackKey->isEmpty() || $height[$i] <= $height[$stackKey->top()]) {
    8. $stackKey->push($i);
    9. } else {
    10. while (!$stackKey->isEmpty() && $height[$i] > $height[$stackKey->top()]) {
    11. $top = $stackKey->pop();
    12. if (!$stackKey->isEmpty()) {
    13. $volume += ($i - $stackKey->top() + 1) * (min($height[$i], $height[$stackKey->top()]) - $height[$top]);
    14. }
    15. }
    16. }
    17. }
    18. return $volume;
    19. }
    20. }
    21. $height = [0,1,0,2,1,0,1,3,2,1,2,1];
    22. $cls = new Solution();
    23. $volume = $cls->trap($height);
    24. echo $volume;