本文正在参加「Java主题月 - Java 刷题打卡」,详情查看 活动链接
题目描述
在MATLAB中,有一个非常有用的函数 reshape,它可以将一个矩阵重塑为另一个大小不同的新矩阵,但保留其原始数据。
给出一个由二维数组表示的矩阵,以及两个正整数r和c,分别表示想要的重构的矩阵的行数和列数。
重构后的矩阵需要将原始矩阵的所有元素以相同的行遍历顺序填充。
如果具有给定参数的reshape操作是可行且合理的,则输出新的重塑矩阵;否则,输出原始矩阵。
示例 1:
输入:
nums =
[[1,2],
[3,4]]
r = 1, c = 4
输出:
[[1,2,3,4]]
解释:
行遍历nums的结果是 [1,2,3,4]。新的矩阵是 1 * 4 矩阵, 用之前的元素值一行一行填充新矩阵。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reshape-the-matrix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路分析
- 这个题目是矩阵转换题目,首先可以用朴素算法解决问题。时间复杂度较高!
- 这个题目更优解是采用数学公式计算的方式,直接计算出新的位置!效率高!可见,数学好在计算机应用中很重要!
AC代码
public class DayCode {
public static void main(String[] args) {
int[][] nums = new int[][]{{1, 2}, {3, 4}};
int r = 1;
int c = 4;
int[][] ans = new DayCode().matrixReshape(nums, r, c);
System.out.println("ans is " + Arrays.deepToString(ans));
}
/**
* https://leetcode-cn.com/problems/reshape-the-matrix/
* @param nums
* @param r
* @param c
* @return
*/
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[][] ans = new int[r][c];
int newX = 0;
int newY = 0;
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < nums[i].length; j++) {
ans[newX][newY] = nums[i][j];
newY++;
if (newY >= c) {
newX++;
newY = 0;
}
}
}
return ans;
}
/**
* https://leetcode-cn.com/problems/reshape-the-matrix/
* @param nums
* @param r
* @param c
* @return
*/
public int[][] matrixReshape2(int[][] nums, int r, int c) {
int m = nums.length;
int n = nums[0].length;
if (m * n != r * c) {
return nums;
}
int[][] ans = new int[r][c];
for (int x = 0; x < m * n; x++) {
ans[x / c][x % c] = nums[x / n][x % n];
}
return ans;
}
}
提交测试:
顺利AC!
总结
- 方法一的时间复杂度是O(n * n),空间复杂度是O(1)
- 方法二的时间复杂度是O(n),空间复杂度是O(1)
- 我写的时候,只想到了方法一,没有想到方法二,继续加油!多写多练!
- 坚持每日一题,加油!