You're given a matrix represented by a two-dimensional array, and two positive integers r and c representing the row number and column number of the wanted reshaped matrix, respectively.
The reshaped matrix needs to be filled with all the elements of the original matrix in the same row-traversing order as they were.
The reshaped matrix needs to be filled with all the elements of the original matrix in the same row-traversing order as they were.
Example 1:
Input:
nums =
[[1,2],
[3,4]]
r = 1, c = 4
Output:
[[1,2,3,4]]
Approach
Java
import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class ReshapeMatrix {public static void main(String[] args) {int mat[][] = { { 1, 2 }, { 3, 4 } };int r = 4, c = 1;mat = matrixReshape(mat, r, c);for (int i = 0; i < mat.length; i++) {System.out.println(Arrays.toString(mat[i]));}}// resaphe the matrix into the new// dimensionsstatic int[][] matrixReshape(int[][] nums, int r, int c) {int n = nums.length;int m = nums[0].length;// if new dimensions are not match// then return the original matrixif (n * m != r * c)return nums;else {int[][] v = new int[r][c];List<Integer> p = new ArrayList<Integer>();for (int i = 0; i < n; i++) {for (int j = 0; j < m; j++) {p.add(nums[i][j]);}}int j = 0;int cnt = 0;int k = 0;for (int i = 0; i < p.size(); i++) {v[j][k] = p.get(i);k++;cnt++;if (cnt == c) {cnt = 0;k = 0;j++;}}return v;}}}
C++
#include <bits/stdc++.h>using namespace std;//resaphe the matrix into the new//dimensionsvector<vector<int>> matrixReshape(vector<vector<int>>& nums,int r, int c){vector<vector<int>> v;int n=nums.size();int m=nums[0].size();//if new dimensions are not match//then return the original matrixif(n*m!=r*c)return nums;else{vector<int> p;for(int i=0;i<n;i++){for(int j=0;j<m;j++){p.push_back(nums[i][j]);}}vector<int> x;for(int i=0;i<p.size();i++){x.push_back(p[i]);if(x.size()==c){v.push_back(x);x.clear();}}return v;}}int main(){vector<vector<int>> nums = {{1,2},{3,4}};int r = 1, c = 4;vector<vector<int>> res=matrixReshape(nums,r,c);cout<<"[";for(int i=0;i<r;i++){cout<<"[";for(int j=0;j<c;j++){if(j!=c-1)cout<<res[i][j]<<",";elsecout<<res[i][j];}if(i!=r-1)cout<<"],";elsecout<<"]";}cout<<"]";}
No comments:
Post a Comment