LeetCode - Easy - 566. Reshape the Matrix

Topic

  • Array

Description

https://leetcode.com/problems/reshape-the-matrix/

In MATLAB, there is a handy function called reshape which can reshape an m x n matrix into a new one with a different size r x c keeping its original data.

You are given an m x n matrix mat and two integers r and c representing the row number and column number of the wanted reshaped matrix.

The reshaped matrix should be filled with all the elements of the original matrix in the same row-traversing order as they were.

If the reshape operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.

Example 1:

Input: mat = [[1,2],[3,4]], r = 1, c = 4
Output: [[1,2,3,4]]

Example 2:

Input: mat = [[1,2],[3,4]], r = 2, c = 4
Output: [[1,2],[3,4]]

Constraints:

  • m == mat.length
  • n == mat[i].length
  • 1 <= m, n <= 100
  • -1000 <= mat[i][j] <= 1000
  • 1 <= r, c <= 300

Analysis

Submission

public class ReshapeTheMatrix {
    public int[][] matrixReshape(int[][] mat, int r, int c) {
        if(mat.length * mat[0].length != r * c)
        	return mat;
    	
        int[][] result = new int[r][c]; 
    	int rp = 0, cp = 0;
        
        for(int[] array : mat) 
        	for(int i : array) {
        		result[rp][cp++] = i;
        		if(cp == c) {
        			rp++;
        			cp = 0;
        		}
        	}
        
    	return result;
    }
}

Test

import static org.junit.Assert.*;
import org.junit.Test;

public class ReshapeTheMatrixTest {

	@Test
	public void test() {
		ReshapeTheMatrix obj = new ReshapeTheMatrix();

		int[][] result1 = obj.matrixReshape(new int[][] {{1, 2}, {3, 4}}, 1, 4);
		int[][] expected1 = {{1, 2, 3, 4}};
		for(int i = 0; i &lt; expected1.length; i++) 
			assertArrayEquals(expected1[i], result1[i]);

		
		int[][] result2 = obj.matrixReshape(new int[][] {{1, 2}, {3, 4}}, 2, 4);
		int[][] expected2 = {{1, 2}, {3, 4}};
		for(int i = 0; i &lt; expected2.length; i++)
			assertArrayEquals(expected2[i], result2[i]);
		
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章