【Lintcode】1170. Reshape the Matrix

题目地址:

https://www.lintcode.com/problem/reshape-the-matrix/description

给定一个二维矩阵 A A A,再给定两个正整数 r r r c c c,要求将 A A A变换为 r r r c c c列的矩阵,并且保持行遍历相同。如果无法变换,则返回原矩阵,否则返回变换后的答案。

能变换当且仅当 A A A的元素个数等于 r c rc rc。判断完之后将原矩阵的数填到新矩阵里即可。代码如下:

public class Solution {
    /**
     * @param nums: List[List[int]]
     * @param r:    an integer
     * @param c:    an integer
     * @return: return List[List[int]]
     */
    public int[][] matrixReshape(int[][] nums, int r, int c) {
        // write your code here
        int m = nums.length, n = nums[0].length;
        if (m * n != r * c) {
            return nums;
        }
        
        int[][] res = new int[r][c];
        for (int idx = 0, i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                res[idx / c][idx % c] = nums[i][j];
                idx++;
            }
        }
        
        return res;
    }
}

时空复杂度 O ( m n ) O(mn) O(mn)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值