题目:https://leetcode-cn.com/problems/trapping-rain-water/
给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。
我的方法一:双指针
步骤
虽然官方解法也是双指针,但是明显官方的解法的更简洁,所以主要看看官方的方法,https://leetcode-cn.com/problems/trapping-rain-water/solution/jie-yu-shui-by-leetcode-solution-tuvc/
class Solution {
public:
int trap(vector<int>& height) {
int ans = 0;
int left = 0, right = height.size() - 1;
int leftMax = 0, rightMax = 0;
while (left < right) {
leftMax = max(leftMax, height[left]);
rightMax = max(rightMax, height[right]);
if (height[left] < height[right]) {
ans += leftMax - height[left];
++left;
} else {
ans += rightMax - height[right];
--right;
}
}
return ans;
}
};
我的解法麻烦
class Solution {
public:
int trap(vector<int>& height) {
if(height.size()<3){
return 0;
}
int sum = 0;
int left = 0;
int right = height.size()-1;
int left_height=0;
int right_height=0;
int lower_height;
int scanned_height=0;
while(left<right){
left_height = height[left];
right_height = height[right];
lower_height = left_height<right_height?left_height:right_height;
if(lower_height<=scanned_height){
if(left_height>right_height){
right--;
}else{
left++;
}
continue;
}
for(int i = left+1; i<right; i++){
if(height[i]<lower_height){
if(height[i]>=scanned_height){
sum += lower_height-height[i];
}else{
sum += lower_height-scanned_height;
}
}
}
if(left_height>right_height){
right--;
}else{
left++;
}
scanned_height=lower_height;
}
return sum;
}
};
网友评论