题目来源
题目描述
题目解析
- 判断是否重构矩阵: r * c == 原始元素个数
不使用额外空间
循环填充即可
- java
if (nums.length * nums[0].length != r * c){
return nums;
}
int[][] ans = new int[r][c];
int row = 0;
int line = 0;
for (int i = 0; i < nums.length; i++){
for (int j = 0; j < nums[i].length; j++){
ans[row][line] = nums[i][j];
line++;
if (line == c){
row++;
line = 0;
}
}
}
return ans;
- cpp
vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {
if(r * c != mat.size() * mat[0].size()){
return mat;
}
int row = 0, line = 0;
std::vector<std::vector<int>> ans (r, std::vector<int>(c, 0));
for (int i = 0; i < mat.size(); ++i) {
for (int j = 0; j < mat[i].size(); ++j) {
ans[row][line++] = mat[i][i];
if(line == c){
++row;
line = 0;
}
}
}
return ans;
}
除法和取模
在上一种方法中,我们需要跟踪我们何时到达结果矩阵的列的末尾,并且需要通过每次检查当前索引来更新当前行和列号以放置提取的元素。我们可以利用数学来帮助解决,而不是在每一步都进行限制性检查。
- cpp
vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {
if(r * c == mat.size() * mat[0].size()){
return mat;
}
int count = 0;
std::vector<std::vector<int>> ans(r, std::vector<int>(c));
for (int i = 0; i < mat.size() * mat[0].size(); ++i) {
ans[count / c][count % c] = mat[i / mat[0].size()][i % mat[0].size()];
count++;
}
return ans;
}
- java
package com.company;
import java.util.*;
public class Solution {
/*
给定矩阵的宽和高范围在 [1, 100]。
给定的 r 和 c 都是正数
*/
public static int[][] matrixReshape(int[][] nums, int r, int c) {
if (nums.length * nums[0].length != r * c){
return nums;
}
int[][] ans = new int[r][c];
int count = 0;
for (int i = 0; i < nums.length; i++){
for (int j = 0; j < nums[i].length; j++){
ans[count / c][count % c] = nums[i][j];
count++;
}
}
return ans;
}
public static void main(String[] args) {
System.out.println(Arrays.deepToString(matrixReshape(new int[][] {
{1,2,3,4},
{5,1,2,3},
{9,5,1,6}
}, 4, 3
)));
}
}
使用队列
队列是先进先出的
public static int[][] matrixReshape(int[][] nums, int r, int c) {
if (nums.length * nums[0].length != r * c){
return nums;
}
// 将数组依次读入队列中
Queue<Integer> query = new LinkedList<>();
for (int i = 0; i < nums.length; i++){
for (int j = 0; j < nums[i].length; j++){
query.add(nums[i][j]);
}
}
int[][] ans = new int[r][c];
for (int i = 0; i < ans.length; i++){
for (int j = 0; j < ans[i].length; j++){
ans[i][j] = query.remove();
}
}
return ans;
}
vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {
if(r * c != mat.size() * mat[0].size()){
return mat;
}
std::queue<int> queue;
for (int i = 0; i < mat.size(); ++i) {
for (int j = 0; j < mat[i].size(); ++j) {
queue.push(mat[i][j]);
}
}
std::vector<std::vector<int>> ans(r, std::vector<int>(c));
for (int i = 0; i < r; ++i) {
for (int j = 0; j < c; ++j) {
ans[i][j] = queue.front();
queue.pop();
}
}
return ans;
}