LeetCode Solutions
566. Reshape the Matrix
Time: $O(rc)$ Space: $O(rc)$
class Solution {
public:
vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
if (nums.empty() || r * c != nums.size() * nums[0].size())
return nums;
vector<vector<int>> ans(r, vector<int>(c));
int k = 0;
for (const vector<int>& row : nums)
for (const int num : row) {
ans[k / c][k % c] = num;
++k;
}
return ans;
}
};
class Solution {
public int[][] matrixReshape(int[][] nums, int r, int c) {
if (nums.length == 0 || r * c != nums.length * nums[0].length)
return nums;
int[][] ans = new int[r][c];
int k = 0;
for (int[] row : nums)
for (final int num : row) {
ans[k / c][k % c] = num;
++k;
}
return ans;
}
}
class Solution:
def matrixReshape(self, nums: List[List[int]], r: int, c: int) -> List[List[int]]:
if nums == [] or r * c != len(nums) * len(nums[0]):
return nums
ans = [[0 for j in range(c)] for i in range(r)]
k = 0
for row in nums:
for num in row:
ans[k // c][k % c] = num
k += 1
return ans