Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

C++ #58

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open

C++ #58

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions LeetCode/Trapping-Rain-Water/C++.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
#include <bits/stdc++.h>
using namespace std;


class Solution {
public:
int trap(vector<int>& height) {
int l = 0, r = height.size() - 1, water = 0, minHeight = 0;
while (l < r) {
while (l < r && height[l] <= minHeight) {
water += minHeight - height[l++];
}
while (l < r && height[r] <= minHeight) {
water += minHeight - height[r--];
}
minHeight = min(height[l], height[r]);
}
return water;
}
};
7 changes: 7 additions & 0 deletions LeetCode/Trapping-Rain-Water/ReadmeForcpp.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Intuition for my code:

Set two pointers l and r to the left and right end of height.
Then we get the minimum height (minHeight) of these pointers since the level of the water cannot be higher than it.
Then we move the two pointers towards the center.
If the coming level is less than minHeight, then it will hold some water.
Fill the water until we meet some "barrier" (with height larger than minHeight) and update l and r to repeat this process
Loading