標(biāo)簽: C++ 算法 LeetCode 數(shù)組
每日算法——leetcode系列
問題 Trapping Rain Water
Difficulty: Hard
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
For example,
Given[0,1,0,2,1,0,1,3,2,1,2,1]
, return6
.
<small>The above elevation map is represented by array [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. Thanks Marcos for contributing this image!</small>
class Solution {
public:
int trap(vector<int>& height) {
}
};
翻譯
困住的雨水
難度系數(shù):困難
給定n個代表地圖中的高度的非負(fù)數(shù)的整數(shù),每條的寬度為1蚁袭,求下雨后能困住多少雨水阿纤。
例如:
給定[0,1,0,2,1,0,1,3,2,1,2,1]
, 返回 6
.
思路
- 先找到最高的條柱
- 再兩邊往中間掃
- 掃左邊時,如果當(dāng)前柱左邊的最大值是當(dāng)前柱澳骤,就記錄
- 不是當(dāng)前柱,剛把水累加
代碼
class Solution {
public:
int trap(vector<int>& height) {
int maxBarIndex = 0;
int index = 0;
for (auto item : height){
if (item > height.at(maxBarIndex)){
maxBarIndex = index;
}
index++;
}
int water = 0;
for (int i = 0, leftMax = 0; i < maxBarIndex; ++i){
if (height[i] > leftMax){
leftMax = height[i];
} else {
water += leftMax - height[i];
}
}
int n = static_cast<int>(height.size());
for (int i = n - 1, rightMax = 0; i > maxBarIndex; --i){
if (height[i] > rightMax) {
rightMax = height[i];
} else {
water += rightMax - height[i];
}
}
return water;
}
};
此題還有一種有棧的方式,以后再碼眶掌。