Skip to content

Latest commit

 

History

History
62 lines (44 loc) · 1.14 KB

File metadata and controls

62 lines (44 loc) · 1.14 KB

867. Transpose Matrix

Leetcode link

解题思路

题目要求一个沿着主轴转置的矩阵

一个简单的思路就是创建一个新的矩阵,但是长跟宽要跟原来的相反

之后遍历旧的矩阵,将行与列的下标呼唤赋值到新的矩阵就好

C++

class Solution {
public:
    vector<vector<int>> transpose(vector<vector<int>>& matrix) {
        int m = matrix.size();
        int n = matrix[0].size();
        vector<vector<int>> res(n, vector<int>(m, 0));
        for(int i=0;i<n;i++) {
            for(int j=0;j<m;j++) {
                res[i][j] = matrix[j][i];
            }
        }
        return res;
    }
};

Javascript

/**
 * @param {number[][]} matrix
 * @return {number[][]}
 */
var transpose = function(matrix) {
    let m = matrix.length;
    let n = matrix[0].length;    
    let res = new Array(n);
    for(let i=0;i<res.length;i++) {
        res[i] = new Array(m).fill(0);
    }
    
    for(let i=0;i<n;i++) {
        for(let j=0;j<m;j++) {
            res[i][j] = matrix[j][i];
        }
    }
    
    return res;
};