刷题-力扣-867. 转置矩阵

867. 转置矩阵

题目链接

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/transpose-matrix/submissions/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题目描述

给你一个二维整数数组 matrix, 返回 matrix 的 转置矩阵 。
矩阵的 转置 是指将矩阵的主对角线翻转,交换矩阵的行索引与列索引。

示例 1:

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

示例 2:

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

提示:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 1000
  • 1 <= m * n <= 105
  • -109 <= matrix[i][j] <= 109

题目分析

  1. 根据题目描述返回矩阵的转置
  2. 按照一列一列的方式遍历matrix,把matrix的每一列转换为一行matrixRow
  3. 再把matrixRow添加到res中

代码

class Solution {
public:
    vector<vector<int>> transpose(vector<vector<int>>& matrix) {
        vector<vector<int>> res;
        for (int col = 0; col < matrix[0].size(); col++) {
            vector<int> matrixRow;
            for (int row = 0; row < matrix.size(); row++) {
                matrixRow.push_back(matrix[row][col]);
            }
            res.push_back(matrixRow);
        }
        return res;
    }
};
posted @ 2021-02-25 19:58  韩亚光  阅读(52)  评论(0编辑  收藏  举报