各位题友大家好! 今天是 @负雪明烛 坚持日更的第 24 天。今天力扣上的每日一题是「566. 重塑矩阵」。

解题思路

思路比较简单:
1. 如果题目给出的矩阵元素个数不等于 $r * c$,那么无法转换,返回原数组;
2. 新建一个 $r$ 行、$c$ 列的新数组;
3. 按行遍历原数组的每个位置,并用 $row$ 和 $col$ 保存应在新数组中填充的当前位置,把原数组的元素放到新数组中的对应位置中。

$row$ 和 $col$ 的变更规则是:每次遍历到一个新位置,则 $col += 1$;如果 $col == c$,说明到了新数组的列的右边界,需要换行,所有$row += 1$, $col += 1$。

代码

  1. class Solution(object):
  2. def matrixReshape(self, nums, r, c):
  3. """
  4. :type nums: List[List[int]]
  5. :type r: int
  6. :type c: int
  7. :rtype: List[List[int]]
  8. """
  9. M, N = len(nums), len(nums[0])
  10. if M * N != r * c:
  11. return nums
  12. res = [[0] * c for _ in range(r)]
  13. row, col = 0, 0
  14. for i in range(M):
  15. for j in range(N):
  16. if col == c:
  17. row += 1
  18. col = 0
  19. res[row][col] = nums[i][j]
  20. col += 1
  21. return res
  1. class Solution {
  2. public:
  3. vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
  4. int M = nums.size();
  5. int N = nums[0].size();
  6. if (M * N != r * c) {
  7. return nums;
  8. }
  9. vector<vector<int>> res(r, vector<int>(c, 0));
  10. int row = 0;
  11. int col = 0;
  12. for (int i = 0; i < M; ++i) {
  13. for (int j = 0; j < N; ++j) {
  14. if (col == c) {
  15. row += 1;
  16. col = 0;
  17. }
  18. res[row][col] = nums[i][j];
  19. col += 1;
  20. }
  21. }
  22. return res;
  23. }
  24. };
class Solution {
    public int[][] matrixReshape(int[][] nums, int r, int c) {
        int M = nums.length;
        int N = nums[0].length;
        if (M * N != r * c) {
            return nums;
        }
        int[][] res = new int[r][c];
        int row = 0, col = 0;
        for (int i = 0; i < M; i++) {
            for (int j = 0; j < N; j++) {
                if (col == c) {
                    row += 1;
                    col = 0;
                }
                res[row][col] = nums[i][j];
                col += 1;
            }
        }
        return res;
    }
}

刷题心得

  1. 今天的题目也可以直接用除法做,可以参考官方题解。
    2. 我组织了模拟面试,今天会当两场面试官,就不做动图了。有兴趣参加或者围观的同学,从我的主页进刷题组织。

OK,以上就是 @负雪明烛 写的今天题解的全部内容了,如果你觉得有帮助的话,求赞、求关注、求收藏。如果有疑问的话,请在下面评论,我会及时解答。

关注我,你将不会错过我的精彩动画题解、面试题分享、组队刷题活动,进入主页 @负雪明烛 右侧有刷题组织,从此刷题不再孤单。

祝大家牛年大吉!AC 多多,Offer 多多!我们明天再见!