River Sizes算法代码功能正常但提示内存泄漏/超时,求问题排查
问题解答
什么是内存泄漏
内存泄漏指程序运行过程中,已经不再需要使用的内存空间没有被垃圾回收机制正常释放,导致内存占用持续上涨,最终耗尽运行内存的异常情况。你遇到的报错本质是内存溢出,不属于严格的内存泄漏,是代码实现逻辑有缺陷导致的。
代码存在的问题
- 节点入队时未提前标记为已访问:你当前的逻辑是节点从队列取出时才标记
isVisitedMatrix为true,这会导致同一个未访问的邻居节点,可能被多个相邻的节点先后检测到,被多次推入队列,同时currLength被重复累加。队列规模会快速膨胀,不仅计算结果错误,还会快速耗尽内存。 - 递归实现BFS逻辑:BFS本身是层级遍历逻辑,使用递归实现会让调用栈深度和队列处理次数完全绑定,只要河流长度超过JS引擎的最大调用栈限制(通常为数千到数万层),就会直接触发栈溢出报错。
- 冗余的
Node类:你完全可以用[row, col]数组存储坐标,不需要额外定义类创建实例,减少不必要的内存开销。
修正后的代码
function riverSizes(matrix) { const rows = matrix.length; if (rows === 0) return []; const cols = matrix[0].length; const isVisitedMatrix = Array(rows).fill(false).map(() => Array(cols).fill(false)); const lengthMatrix = []; // 四个遍历方向 const dirs = [[-1,0],[1,0],[0,-1],[0,1]]; for (let row = 0; row < rows; row++) { for (let col = 0; col < cols; col++) { if (isVisitedMatrix[row][col] || matrix[row][col] === 0) continue; // 迭代实现BFS const queue = [[row, col]]; isVisitedMatrix[row][col] = true; let currLength = 1; while (queue.length > 0) { const [currRow, currCol] = queue.shift(); for (const [dx, dy] of dirs) { const newRow = currRow + dx; const newCol = currCol + dy; if (newRow >=0 && newRow < rows && newCol >=0 && newCol < cols && !isVisitedMatrix[newRow][newCol] && matrix[newRow][newCol] === 1) { isVisitedMatrix[newRow][newCol] = true; currLength++; queue.push([newRow, newCol]); } } } lengthMatrix.push(currLength); } } return lengthMatrix; }
用你给出的样例输入测试,返回的数组排序后和样例输出[1,2,2,2,5]一致。
内容的提问来源于stack exchange,提问作者rann
相关产品推荐
相关产品推荐

