接雨水算法解析与多语言翻译实现

引言:理解接雨水问题
接雨水(Trapping Rain Water)是一个经典的算法问题,通常出现在技术面试和算法竞赛中。这个问题模拟了在一个由非负整数表示的高度图中,计算能够收集的雨水总量。想象一下,你有一个由柱子组成的地形图,柱子的高度由数组给出,当雨水落下时,水会被困在柱子之间,你需要计算这些被困雨水的总体积。
这个问题的难点在于如何高效地计算雨水量,而不仅仅是暴力枚举所有可能的位置。暴力方法的时间复杂度为O(n^2),对于大规模数据来说效率低下。因此,我们需要更优化的算法,如双指针法或单调栈法,这些方法可以将时间复杂度降低到O(n)。在本文中,我们将详细解析这些算法,并提供多种编程语言的实现代码,包括Python、Java、C++和JavaScript,帮助你全面理解并应用这些解决方案。
接雨水问题的输入是一个整数数组
height
,其中
height[i]
表示第i个位置的高度。输出是一个整数,表示能够收集的雨水总量。例如,对于输入
[0,1,0,2,1,0,1,3,2,1,2,1]
,输出应为6,因为雨水可以被困在多个位置,总积水量为6。接下来,我们将逐步解析算法,并提供详细的代码示例。
算法解析:核心思路
接雨水问题的核心在于理解雨水是如何被“困住”的。雨水不会无限积聚,它受限于左右两侧的最高柱子。具体来说,对于数组中的每个位置i,该位置能够收集的雨水量等于该位置左右两侧最大高度的较小值减去当前位置的高度。用数学公式表示为:
water[i] = min(left_max[i], right_max[i]) – height[i]
其中,
left_max[i]
是从左到右到位置i的最大高度,
right_max[i]
是从右到左到位置i的最大高度。如果
min(left_max[i], right_max[i]) <= height[i] ,则该位置无法积水,积水量为0。 总雨水量就是所有位置的 water[i] 之和。但直接计算每个位置的 left_max 和 right_max 需要O(n)空间和O(n)时间,这已经是优化后的暴力法。更进一步,我们可以使用双指针法或单调栈法来优化空间复杂度到O(1)或O(n)(单调栈通常需要O(n)空间)。 暴力法(基础理解) 暴力法是最直观的实现,但效率低。它对每个位置i,分别向左和向右扫描找到最大高度,然后计算积水量。时间复杂度为O(n^2),空间复杂度为O(1)。这种方法适合小规模数据,但不适合生产环境。 伪代码: def trap_brute(height): n = len(height) total_water = 0 for i in range(1, n-1): # 边界无法积水 left_max = max(height[:i+1]) right_max = max(height[i:]) total_water += max(0, min(left_max, right_max) - height[i]) return total_water 这种方法简单,但效率低。例如,对于 [0,1,0,2,1,0,1,3,2,1,2,1] ,它会逐个计算每个位置的左右最大值,导致重复计算。 双指针法(O(n)时间,O(1)空间) 双指针法是更高效的解决方案。它使用两个指针,一个从左向右(left),一个从右向左(right),同时维护两个变量 left_max 和 right_max ,分别表示从左到右和从右到左的最大高度。 核心思想:如果 height[left] < height[right] ,说明左侧的瓶颈在左边,因此计算 left 位置的积水量;反之,计算 right 位置的积水量。这样可以避免为每个位置计算左右最大值。 步骤: 初始化 left = 0 , right = n-1 , left_max = 0 , right_max = 0 , total_water = 0 。 当 left <= right 时循环: 如果 height[left] <= height[right] : 如果 height[left] >= left_max
,更新
left_max = height[left]
。
否则,
total_water += left_max – height[left]
。
left += 1
。
否则:
如果
height[right] >= right_max
,更新
right_max = height[right]
。
否则,
total_water += right_max – height[right]
。
right -= 1
。
返回
total_water
。
这种方法的时间复杂度为O(n),空间复杂度为O(1),非常高效。
单调栈法(另一种O(n)时间方法)
单调栈法使用一个栈来维护递减的高度序列。当遇到一个比栈顶高的柱子时,说明形成了一个“坑”,可以计算积水量。栈中存储的是索引,而不是高度。
步骤:
初始化一个空栈,
total_water = 0
。
遍历数组,对于每个高度
h
:
当栈非空且
h > height[stack[-1]]
时:
弹出栈顶
top = stack.pop()
。
如果栈为空,跳出循环。
计算宽度:
width = i – stack[-1] – 1
。
计算高度:
bounded_height = min(h, height[stack[-1]]) – height[top]
。
total_water += width * bounded_height
。
将当前索引入栈。
返回
total_water
。
这种方法适合处理复杂地形,但空间复杂度为O(n)。
多语言实现:详细代码示例
下面,我们将为每种算法提供多种编程语言的完整实现。每个实现都包括详细的注释、示例输入输出,以及复杂度分析。我们以输入
height = [0,1,0,2,1,0,1,3,2,1,2,1]
为例,预期输出为6。
1. 双指针法实现
Python实现
def trap(height):
“””
使用双指针法计算接雨水量。
:param height: List[int] – 高度数组
:return: int – 总雨水量
“””
if not height:
return 0

left, right = 0, len(height) – 1
left_max, right_max = 0, 0
total_water = 0

while left <= right: # 优先处理较矮的一侧 if height[left] <= height[right]: if height[left] >= left_max:
left_max = height[left] # 更新左侧最大值
else:
total_water += left_max – height[left] # 计算积水量
left += 1
else:
if height[right] >= right_max:
right_max = height[right] # 更新右侧最大值
else:
total_water += right_max – height[right] # 计算积水量
right -= 1

return total_water

# 示例
height = [0,1,0,2,1,0,1,3,2,1,2,1]
print(trap(height)) # 输出: 6
解释
:这个实现高效且易懂。
left
和
right
指针同时移动,确保每个位置只被访问一次。对于示例,它会正确计算出总积水量为6。
复杂度
:时间O(n),空间O(1)。
Java实现
public class TrapRainWater {
public int trap(int[] height) {
if (height == null || height.length == 0) {
return 0;
}

int left = 0;
int right = height.length – 1;
int leftMax = 0;
int rightMax = 0;
int totalWater = 0;

while (left <= right) { if (height[left] <= height[right]) { if (height[left] >= leftMax) {
leftMax = height[left];
} else {
totalWater += leftMax – height[left];
}
left++;
} else {
if (height[right] >= rightMax) {
rightMax = height[right];
} else {
totalWater += rightMax – height[right];
}
right–;
}
}

return totalWater;
}

public static void main(String[] args) {
TrapRainWater solution = new TrapRainWater();
int[] height = {0,1,0,2,1,0,1,3,2,1,2,1};
System.out.println(solution.trap(height)); // 输出: 6
}
}
解释
:Java版本与Python类似,使用整数变量维护指针和最大值。
main
方法提供测试示例。
复杂度
:时间O(n),空间O(1)。
C++实现
#include
#include
#include

using namespace std;

class Solution {
public:
int trap(vector& height) {
if (height.empty()) return 0;

int left = 0;
int right = height.size() – 1;
int leftMax = 0;
int rightMax = 0;
int totalWater = 0;

while (left <= right) { if (height[left] <= height[right]) { if (height[left] >= leftMax) {
leftMax = height[left];
} else {
totalWater += leftMax – height[left];
}
left++;
} else {
if (height[right] >= rightMax) {
rightMax = height[right];
} else {
totalWater += rightMax – height[right];
}
right–;
}
}

return totalWater;
}
};

int main() {
Solution sol;
vector height = {0,1,0,2,1,0,1,3,2,1,2,1};
cout << sol.trap(height) << endl; // 输出: 6 return 0; } 解释 :C++版本使用 vector 作为输入,逻辑相同。 main 函数编译并运行测试。 复杂度 :时间O(n),空间O(1)。 JavaScript实现 /** * @param {number[]} height * @return {number} */ var trap = function(height) { if (!height || height.length === 0) { return 0; } let left = 0; let right = height.length - 1; let leftMax = 0; let rightMax = 0; let totalWater = 0; while (left <= right) { if (height[left] <= height[right]) { if (height[left] >= leftMax) {
leftMax = height[left];
} else {
totalWater += leftMax – height[left];
}
left++;
} else {
if (height[right] >= rightMax) {
rightMax = height[right];
} else {
totalWater += rightMax – height[right];
}
right–;
}
}

return totalWater;
};

// 示例
const height = [0,1,0,2,1,0,1,3,2,1,2,1];
console.log(trap(height)); // 输出: 6
解释
:JavaScript版本使用
let
声明变量,适合Node.js或浏览器环境。测试输出为6。
复杂度
:时间O(n),空间O(1)。
2. 单调栈法实现
Python实现
def trap_stack(height):
“””
使用单调栈法计算接雨水量。
:param height: List[int] – 高度数组
:return: int – 总雨水量
“””
if not height:
return 0

stack = [] # 存储索引
total_water = 0

for i in range(len(height)):
# 当栈非空且当前高度大于栈顶高度时,计算积水量
while stack and height[i] > height[stack[-1]]:
top = stack.pop() # 弹出栈顶
if not stack:
break # 如果栈空,无法形成坑
# 计算宽度:当前索引 – 新栈顶索引 – 1
width = i – stack[-1] – 1
# 计算高度:min(当前高度, 新栈顶高度) – 弹出的高度
bounded_height = min(height[i], height[stack[-1]]) – height[top]
total_water += width * bounded_height
stack.append(i) # 压入当前索引

return total_water

# 示例
height = [0,1,0,2,1,0,1,3,2,1,2,1]
print(trap_stack(height)) # 输出: 6
解释
:栈维护递减序列。当遇到高柱子时,弹出低柱子并计算积水量。示例中,它会正确处理多个坑。
复杂度
:时间O(n),空间O(n)。
Java实现
import java.util.Stack;

public class TrapRainWaterStack {
public int trap(int[] height) {
if (height == null || height.length == 0) {
return 0;
}

Stack stack = new Stack<>();
int totalWater = 0;

for (int i = 0; i < height.length; i++) { while (!stack.isEmpty() && height[i] > height[stack.peek()]) {
int top = stack.pop();
if (stack.isEmpty()) {
break;
}
int width = i – stack.peek() – 1;
int boundedHeight = Math.min(height[i], height[stack.peek()]) – height[top];
totalWater += width * boundedHeight;
}
stack.push(i);
}

return totalWater;
}

public static void main(String[] args) {
TrapRainWaterStack solution = new TrapRainWaterStack();
int[] height = {0,1,0,2,1,0,1,3,2,1,2,1};
System.out.println(solution.trap(height)); // 输出: 6
}
}
解释
:Java使用
Stack
类,逻辑与Python相同。
复杂度
:时间O(n),空间O(n)。
C++实现
#include
#include
#include
#include

using namespace std;

class Solution {
public:
int trap(vector& height) {
if (height.empty()) return 0;

stack st;
int totalWater = 0;

for (int i = 0; i < height.size(); i++) { while (!st.empty() && height[i] > height[st.top()]) {
int top = st.top();
st.pop();
if (st.empty()) break;
int width = i – st.top() – 1;
int boundedHeight = min(height[i], height[st.top()]) – height[top];
totalWater += width * boundedHeight;
}
st.push(i);
}

return totalWater;
}
};

int main() {
Solution sol;
vector height = {0,1,0,2,1,0,1,3,2,1,2,1};
cout << sol.trap(height) << endl; // 输出: 6 return 0; } 解释 :C++使用 stack
,注意包含必要的头文件。
复杂度
:时间O(n),空间O(n)。
JavaScript实现
/**
* @param {number[]} height
* @return {number}
*/
var trap = function(height) {
if (!height || height.length === 0) {
return 0;
}

let stack = []; // 存储索引
let totalWater = 0;

for (let i = 0; i < height.length; i++) { while (stack.length > 0 && height[i] > height[stack[stack.length – 1]]) {
let top = stack.pop();
if (stack.length === 0) {
break;
}
let width = i – stack[stack.length – 1] – 1;
let boundedHeight = Math.min(height[i], height[stack[stack.length – 1]]) – height[top];
totalWater += width * boundedHeight;
}
stack.push(i);
}

return totalWater;
};

// 示例
const height = [0,1,0,2,1,0,1,3,2,1,2,1];
console.log(trap(height)); // 输出: 6
解释
:JavaScript使用数组模拟栈,
pop()
和
push()
操作。
复杂度
:时间O(n),空间O(n)。
算法比较与优化建议
双指针法
:空间最优(O(1)),适合内存受限环境。缺点是逻辑稍复杂,但易于实现。
单调栈法
:直观易懂,适合理解地形坑的形成,但空间O(n)。在面试中,如果要求空间优化,优先双指针。
暴力法
:仅用于教学,不推荐实际使用。
优化提示:处理边界情况,如空数组或单个元素。测试用例应包括全零、递增/递减数组。
结论
接雨水问题是算法基础的绝佳练习,掌握双指针和单调栈法能提升你的编程能力。通过以上多语言实现,你可以根据项目需求选择合适语言。实践时,建议用LeetCode等平台测试。如果你有特定语言或变体需求,欢迎进一步讨论!