leeguoo 的个人博客 leeguoo 的个人博客

If you stay positive, you have a shot at a silver lining.

目录
经典面试题:顺时针打印矩阵(javascript解法)
/    

经典面试题:顺时针打印矩阵(javascript解法)

经典面试题 顺时针打印矩阵

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。

示例 1:

输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]

示例 2:

输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]

限制:

  • 0 <= matrix.length <= 100
  • 0 <= matrix[i].length <= 100

第一次尝试解法

/**
 * @param {number[][]} matrix
 * @return {number[]}
 */
var spiralOrder = function(matrix) {
    let result = [];
    while(matrix.length>0){
        // 从左到右
        result = result.concat(matrix[0]);
        matrix.splice(0,1)
        // 从上到下
        if(matrix.length === 0) break;
        for(let i = 0; i< matrix.length; i++){
            result.push(matrix[i][matrix[i].length-1]);
            if(matrix[i].length === 1) {
                matrix.splice(i, 1);
                i--;
            }else{
                matrix[i].splice(matrix[i].length-1, 1);
            }
        }
        // 从右到左
        if(matrix.length === 0) break;
        for(let i = matrix[matrix.length - 1].length - 1; i >= 0 ; i--){
            result.push(matrix[matrix.length - 1][i]);
        }
        matrix.splice(matrix.length - 1, 1);
        // 从下到上
        if(matrix.length === 0) break;
        for(let i = matrix.length - 1; i >= 0 ; i--){
            result.push(matrix[i][0]);
            if(matrix[i].length === 1) {
                matrix.splice(i, 1);
            }else{
                matrix[i].splice(0,1);
            }
        }
    }

    return result;
};

优化解法

// 删除元素太浪费性能, 所以改成记录上下左右索引位置的方式
/**
 * @param {number[][]} matrix
 * @return {number[]}
 */
var spiralOrder = function(matrix) {
    if(matrix.length === 0)return [];
    const result = [];
    let top = 0, right = matrix[0].length - 1, bottom = matrix.length - 1, left = 0;
    while(top < bottom && left < right){
        for(let i = left; i <= right; i++)result.push(matrix[top][i]);
        for(let i = top + 1; i <= bottom; i++)result.push(matrix[i][right]);
        for(let i = right - 1; i >= left; i--)result.push(matrix[bottom][i]);
        for(let i = bottom - 1; i > top; i--)result.push(matrix[i][left]);
        top++;
        right--;
        bottom--;
        left++;
    }
    if(top === bottom)for(let i = left; i <= right; i++)result.push(matrix[bottom][i]);
    else if(right === left)for(let i = top; i <= bottom; i++)result.push(matrix[i][right]);
    return result;
};

标题:经典面试题:顺时针打印矩阵(javascript解法)
作者:leeguooooo
地址:https://leeguoo.com/articles/2020/06/06/1591379559684.html