Java One loop O(n)time


  • 0
    
    public class Solution {
        public int[][] matrixReshape(int[][] nums, int r, int c) {
            int oldW=nums[0].length;
            int oldSize=nums.length*oldW;
            int newSize=r*c;
            
            if(oldSize!=newSize){
                return nums;
            }
            
            int[][] newN=new int[r][c];
            
            
            for(int i=0;i<r;i++){
                for(int j=0;j<c;j++){
                    newN[i][j]=nums[(i*c+j)/oldW][(i*c+j)%oldW];//(i*c+j)-(i*c+j)/oldW*oldW   (i*c+j)/oldW
                }
            }
    
            
            return newN;
        }
    }
    
    

Log in to reply
 

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