ARTICLE DETAIL

资讯详情

深耕郑州网站建设与运营推广的一线实战洞察。

Kimi LeetCode 54. 螺旋矩阵 Rust实现

Kimi    LeetCode 54. 螺旋矩阵 Rust实现 LeetCode 54. 螺旋矩阵Rust 实现。思路维护四个边界按顺时针逐层收缩遍历从左到右遍历top行top从上到下遍历right列right--从右到左遍历bottom行bottom--需检查是否还有行从下到上遍历left列left需检查是否还有列Rust 实现implSolution{pubfnspiral_order(matrix:VecVeci32)-Veci32{ifmatrix.is_empty()||matrix[0].is_empty(){returnvec![];}letmmatrix.len();letnmatrix[0].len();letmuttop:usize0;letmutbottomm-1;letmutleft:usize0;letmutrightn-1;letmutresultVec::with_capacity(m*n);whiletopbottomleftright{// 1. 从左到右遍历 top 行forcolinleft..right{result.push(matrix[top][col]);}top1;// 2. 从上到下遍历 right 列forrowintop..bottom{result.push(matrix[row][right]);}ifright0{break;}right-1;// 3. 从右到左遍历 bottom 行需检查是否还有行iftopbottom{forcolin(left..right).rev(){result.push(matrix[bottom][col]);}ifbottom0{break;}bottom-1;}// 4. 从下到上遍历 left 列需检查是否还有列ifleftright{forrowin(top..bottom).rev(){result.push(matrix[row][left]);}left1;}}result}}复杂度时间复杂度O(m × n)空间复杂度O(1)不计输出数组关键点步骤 3 和 4 需要加if判断防止单行/单列时重复遍历right和bottom在减 1 前需要判断是否为 0避免usize下溢..表示闭区间范围rev()用于反向遍历
返回列表