meibin08 / free-programming-books

📚码农周报 免费的编程书籍,leetcode(力扣)题解、前端算法题,牛客网前端大厂面试题题解、提升工作效率的常用工具等📈🎉
https://susouth.com/
424 stars 60 forks source link

Array-解题:旋转图像(NO.48) #38

Open meibin08 opened 5 years ago

meibin08 commented 5 years ago

给定一个 n × n 的二维矩阵表示一个图像。

将图像顺时针旋转 90 度。

给定 matrix = 
[
  [1,2,3],
  [4,5,6],
  [7,8,9]
],

原地旋转输入矩阵,使其变为:
[
  [7,4,1],
  [8,5,2],
  [9,6,3]
]
给定 matrix =
[
  [ 5, 1, 9,11],
  [ 2, 4, 8,10],
  [13, 3, 6, 7],
  [15,14,12,16]
], 

原地旋转输入矩阵,使其变为:
[
  [15,13, 2, 5],
  [14, 3, 4, 1],
  [12, 6, 8, 9],
  [16, 7,10,11]
]

原题链接:https://leetcode-cn.com/problems/rotate-image/

meibin08 commented 5 years ago

js解题思路:


/**
 * @param {number[][]} matrix
 * @return {void} Do not return anything, modify matrix in-place instead.
 */
var rotate = function (matrix) {
    var cloneArr = matrix.toString().split(",");

    var len = matrix.length;
    var index = 0;
    for (var i = len - 1; i >= 0; i--) {
        var item = cloneArr.slice(index * len, (index + 1) * len);

        for (var u = 0; u < len; u++) {
            matrix[u][i] = item[u]

        };
        index++;
    };
    return matrix;
};