重塑矩阵(vector和java二维数组的学习leetocde566 )-------------------c++/java实现
题目表述
在 MATLAB 中,有一个非常有用的函数 reshape ,它可以将一个 m x n 矩阵重塑为另一个大小不同(r x c)的新矩阵,但保留其原始数据。
给你一个由二维数组 mat 表示的 m x n 矩阵,以及两个正整数 r 和 c ,分别表示想要的重构的矩阵的行数和列数。
重构后的矩阵需要将原始矩阵的所有元素以相同的 行遍历顺序 填充。
如果具有给定参数的 reshape 操作是可行且合理的,则输出新的重塑矩阵;否则,输出原始矩阵。
样例
输入:mat = [[1,2],[3,4]], r = 1, c = 4
输出:[[1,2,3,4]]
条件
m == mat.length
n == mat[i].length
1 <= m, n <= 100
-1000 <= mat[i][j] <= 1000
1 <= r, c <= 300
思路
c++和java再被调用函数中创建vector(数组)后
返回vector(数组)名后用一个未申请空间的二维vector(数组)变量接收返回值,即可得到被处理后的vector(数组)。
注意点
注意前后传参是数组指针的问题!
知识点
vector的创建,vector二维的创建
ac代码
c++:
#include <iostream>
#include<vector>
using namespace std;
class Solution {
public:
vector<vector<int> > matrixReshape(vector<vector<int> >& mat, int r, int c) {
// cout<<"函数进入"<<endl;
int length=mat.size();
int line = mat[0].size();
int x=0,y=0;
if(r*c!=length*line){
return mat;
}
vector<vector<int> > ans(r,vector<int>(c));
for(int i=0;i<r;i++)
for(int j=0;j<c;j++)
{
ans[i][j]=mat[x][y];
if(y==(line-1))
{
x++;
y=0;
}
else
y++;
}
//cout<<"函数结束"<<endl;
// for(int i=0;i<r;i++)
// for(int j=0;j<c;j++)
// cout<<"fu函数输出:"<<ans[i][j];
return ans;
}
};
int main()
{
cout << "Hello world!" << endl;
vector<vector<int> > a;
vector<vector<int> > b(1,vector<int>(4));
for(int i=0;i<4;i++)
b[0][i]=i;
Solution problem;
a=problem.matrixReshape(b,2,2);
// for(int i=0;i<a.size();i++)
// for(int j=0;j<a[0].size();j++)
// cout<<"主函数输出:"<<a[i][j];
return 0;
}
java:
public class Solution {
public int[][] matrixReshape(int[][] mat, int r, int c) {
int length=mat.length;
int line=mat[0].length;
int [][] ans=new int [r][c];
int x=0,y=0;
if(r*c!=length*line)
return mat;
else {
for(int i=0;i<length;i++)
for(int j=0;j<line;j++) {
ans[x][y]=mat[i][j];
if(y==(c-1))
{x++;
y=0;
}
else
y++;
}
}
// for(int i=0;i<r;i++)
// { for(int j=0;j<c;j++)
// System.out.print(ans[i][j]+" ");
// System.out.println();
// }
return ans;
}
}
public class center {
public static void main(String ars[]) {
Solution ans = new Solution();
int [][] mat = new int[4][1];
for(int i=0;i<4;i++)
mat[i][0]=i;
int [][] remat ;
remat = ans.matrixReshape(mat, 2, 2);
for(int i=0;i<2;i++)
for(int j=0;j<2;j++)
System.out.println("主函数输出:"+remat[i][j]);
}
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/squares-of-a-sorted-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。