We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
出处:LeetCode 算法第54题 给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。 示例 1: 输入: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] 输出: [1,2,3,6,9,8,7,4,5] 示例 2: 输入: [ [1, 2, 3, 4], [5, 6, 7, 8], [9,10,11,12] ] 输出: [1,2,3,4,8,12,11,10,9,5,6,7]
出处:LeetCode 算法第54题
给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
示例 1:
输入: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] 输出: [1,2,3,6,9,8,7,4,5]
示例 2:
输入: [ [1, 2, 3, 4], [5, 6, 7, 8], [9,10,11,12] ] 输出: [1,2,3,4,8,12,11,10,9,5,6,7]
定义四个角四个指针,循环遍历四条边
/** * @param {number[][]} matrix * @return {number[]} */ var spiralOrder = function (matrix) { var result = []; var row = matrix.length - 1; var col = matrix[0].length - 1; var r = 0; var c = 0; while (r <= row && c <= col) { for (var i = r; i <= col; i++) { result.push(matrix[r][i]); } r++; for (var i = r; i <= row; i++) { result.push(matrix[i][col]); } col--; if (r <= row) { for (var i = col; i >= c; i--) { result.push(matrix[row][i]); } row--; } if (c <= col) { for (var i = row; i >= r; i--) { result.push(matrix[i][c]); } c++; } } return result; }; console.log(spiralOrder([ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12] ]));
The text was updated successfully, but these errors were encountered:
if(matrix.length < 1) {return [];}
Sorry, something went wrong.
No branches or pull requests
习题
思路
定义四个角四个指针,循环遍历四条边
解答
The text was updated successfully, but these errors were encountered: