Skip to content

42. Trapping Rain Water - #120

Open
kazuki-official wants to merge 1 commit into
mainfrom
42-trapping-rain-water
Open

42. Trapping Rain Water#120
kazuki-official wants to merge 1 commit into
mainfrom
42-trapping-rain-water

Conversation

@kazuki-official

Copy link
Copy Markdown
Owner

Comment thread memo.md
# Step2

## Code2-1
## 他の人のPRをみる

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

参考までに少し前に解いたときのコードを貼ります。 3-pass で解いています。座標 i に溜まる水の量は、 min(i より左の一番高い壁の高さ, i より右の一番高い壁の高さ) - i の高さ を求めています。

class Solution {
public:
    int trap(vector<int>& height) {
        vector<int> max_height_from_left(height.begin(), height.end());
        for (int i = 1; i < height.size(); ++i) {
            max_height_from_left[i] = std::max(max_height_from_left[i], max_height_from_left[i - 1]);
        }

        vector<int> max_height_from_right(height.begin(), height.end());
        for (int i = height.size() - 2; i >= 0; --i) {
            max_height_from_right[i] = std::max(max_height_from_right[i], max_height_from_right[i + 1]);
        }

        int volume = 0;
        for (int i = 0; i < height.size(); ++i) {
            volume += std::min(max_height_from_left[i], max_height_from_right[i]) - height[i];
        }

        return volume;
    }
};

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

3 passの方が意図が明確で読みやすいですね。共有ありがとうございます

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants