Java O(mn) solution


  • 0
    T

    The basic idea is:

    1. put all the elements in a one dimension array
    2. reshape the array to new matrix
    public int[][] matrixReshape(int[][] nums, int r, int c) {
    		int l = nums.length;
    		int w = nums[0].length;
    		if(l * w != r* c)
    			return nums;
    		
    		int[] combined = new int[r*c] ;
    		for(int i = 0; i< nums.length; i++)
    			System.arraycopy(nums[i], 0, combined, nums[i].length * i, nums[i].length);
    		
    		int[][] ret = new int[r][c];
    		for (int i = 0; i < r; i++){
    			ret[i] = Arrays.copyOfRange(combined, c*i, c*i + c );
    		}
    		return ret;
    	}

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.