[LeetCode | C++] July LeetCoding Challenge 2021 — Week 1 Reshape the Matrix (5th, July)

yeahsilver
1 min readJul 6, 2021

📃 Problem

https://leetcode.com/explore/challenge/card/july-leetcoding-challenge-2021/608/week-1-july-1st-july-7th/3803/

💡 Check Point

  1. Determine whether given values r,c are possible and legal.
  2. Determine how to create a reshaped matrix from an original matrix.

👩‍💻 My Solution

class Solution {
public:

vector<vector<int> > matrixReshape(vector<vector<int> >& mat, int r, int c) {
vector<vector<int> > result;

// Define original matrix's row and column
// m = original row, n = original colum
int m = mat.size();
int n = mat[0].size();

// If we could not create a reshaped matrix with using given values c, r
// => return an origianl matrix
if(r*c != m*n) {
return mat;
}


// Otherwise, create a reshaped matrix!
for(int i = 0; i < r; i++) {
vector<int> values;

for(int j = 0; j < c; j++) {
// Define k which calculate a new matrix's 1d index
int k = c * i + j;

// Calculate 2d indices using 1d index
values.push_back(mat[k/n][k%n]);
}

result.push_back(values);
}

return result;
}
};

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

No responses yet

Write a response