Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 6a12484

Browse files
two pointer
1 parent eb8190e commit 6a12484

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
// Source : https://leetcode.com/problems/trapping-rain-water/
2+
// Author : henrytien
3+
// Date : 2022年02月02日
4+
5+
/*****************************************************************************************************
6+
*
7+
* Given n non-negative integers representing an elevation map where the width of each bar is 1,
8+
* compute how much water it can trap after raining.
9+
*
10+
* Example 1:
11+
*
12+
* Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
13+
* Output: 6
14+
* Explanation: The above elevation map (black section) is represented by array
15+
* [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.
16+
*
17+
* Example 2:
18+
*
19+
* Input: height = [4,2,0,3,2,5]
20+
* Output: 9
21+
*
22+
* Constraints:
23+
*
24+
* n == height.length
25+
* 1 <= n <= 2 * 104
26+
* 0 <= height[i] <= 105
27+
******************************************************************************************************/
28+
29+
#include "../inc/ac.h"
30+
class Solution
31+
{
32+
public:
33+
int trap(vector<int> &height)
34+
{
35+
36+
if (height.size() == 0)
37+
{
38+
return 0;
39+
}
40+
int res = 0;
41+
int left = 0, right = height.size() - 1;
42+
int max_left = 0, max_right = 0;
43+
44+
while (left <= right)
45+
{
46+
if (height[left] <= height[right])
47+
{
48+
if (height[left] > max_left)
49+
{
50+
max_left = height[left];
51+
}
52+
else
53+
{
54+
res += max_left - height[left];
55+
}
56+
left++;
57+
}
58+
else
59+
{
60+
if (height[right] > max_right)
61+
{
62+
max_right = height[right];
63+
}
64+
else
65+
{
66+
res += max_right - height[right];
67+
}
68+
right--;
69+
}
70+
}
71+
return res;
72+
}
73+
};
74+
75+
int main()
76+
{
77+
78+
vector<int> height{0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};
79+
cout << Solution().trap(height);
80+
return 0;
81+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /