【LeetCode】数组-5(566)-按照要求输出矩阵

题目要求:

思路一:借助队列,先顺序读入input矩阵,然后按照output要求向output矩阵输入

【正确代码】

 1 class Solution {
 2     public int[][] matrixReshape(int[][] nums, int r, int c) {
 3         int[][] res = new int[r][c];
 4         if (nums == null || nums.length * nums[0].length != r * c) {
 5             return nums;
 6         }
 7         Queue<Integer> queue = new LinkedList<>();
 8         for (int i = 0; i < nums.length; i++) {
 9             for (int j = 0; j < nums[0].length; j++) {
10                 queue.add(nums[i][j]);
11             }
12         }
13         for (int i = 0; i < r; i++) {
14             for (int j = 0; j < c; j++) {
15                 res[i][j] = queue.remove();
16             }
17         }
18         return res;
19     }
20 }

时间复杂度:O(m*n)

空间复杂度:O(m*n)

 

思路二:不借助辅助空间,直接根据output的要求向output矩阵输入

正常向output矩阵中读入数据,如果 cols > c 的话,rows++

【正确代码】(蓝色标记处,第一次写时出错)

 1 class Solution {
 2     public int[][] matrixReshape(int[][] nums, int r, int c) {
 3         int[][] res = new int[r][c];
 4         if (nums == null || nums.length * nums[0].length != r * c) {
 5             return nums;
 6         }
 7         int rows = 0, cols = 0;
 8         for (int i = 0; i < nums.length; i++) {
 9             for (int j = 0; j < nums[0].length; j++) {
10                 res[rows][cols] = nums[i][j];
11                 cols++;
12                 if (cols >= c) {
13                     rows++;
14                     cols = 0;
15                 }
16             }
17         }
18         return res;
19     }
20 }

时间复杂度:O(m*n)

空间复杂度;O(m*n)

 

思路三:使用矩阵转换的公式 nums[ni+j]

满足基本的 nums.length * nums[0].length == r * c 条件情况下,使用矩阵目前的 (长度/c )决定行数,(长度 % c)决定列数

【正确代码】(今天什么状态,刚刚又把count++给丢了「囧」)

 1 class Solution {
 2     public int[][] matrixReshape(int[][] nums, int r, int c) {
 3         int[][] res = new int[r][c];
 4         if (nums == null || nums.length * nums[0].length != r * c) {
 5             return nums;
 6         }
 7         int count = 0;
 8         for (int i = 0; i < nums.length; i++) {
 9             for (int j = 0; j < nums[0].length; j++) {
10                 res[count / c][count % c] = nums[i][j];
11                 count++;
12             }
13         }
14         return res;
15     }
16 }

时间复杂度:O(m*n)

空间复杂度:O(m*n)

posted @ 2017-08-18 21:45  菜鸟更要虚心学习  阅读(308)  评论(0编辑  收藏  举报