One loop


  • 31

    We can use matrix[index / width][index % width] for both the input and the output matrix.

    public int[][] matrixReshape(int[][] nums, int r, int c) {
        int m = nums.length, n = nums[0].length;
        if (r * c != m * n)
            return nums;
        int[][] reshaped = new int[r][c];
        for (int i = 0; i < r * c; i++)
            reshaped[i/c][i%c] = nums[i/n][i%n];
        return reshaped;
    }

  • 0
    S

    @StefanPochmann This seems to take more time than a two loop solution. Though the time complexity is the same O(r*c) for both. Do the '' and '%' operators take more time than an addition/increment?


  • 0
    S

    This is my solution and it seems to run faster. It beats 89% solutions, while single loop beats 60%.

    This is my solution:

    public class Solution {
        public int[][] matrixReshape(int[][] nums, int r, int c) {
            if(nums==null || nums.length==0 || nums[0].length==0 || r<=0 || c<=0) return nums;
            
            int m=nums.length;
            int n=nums[0].length;
            
            if(m*n!=r*c) return nums;
            
            int[][] result= new int[r][c];
            
            int rowm=0, coln=0;
            for(int i=0; i<r;i++){
                for(int j=0; j<c; j++){
                    result[i][j]=nums[rowm][coln];
                    coln++;
                    if(coln==n){
                        rowm++;
                        coln=0;
                    }
                }
            }
            return result;
        }
    }
    

  • 0

    @SM54 said in One loop:

    It beats 89% solutions, while single loop beats 60%.

    It's not clear how you obtained those numbers. How many times did you submit each solution? And are your numbers means or medians or modes or something else? Also, better tell the times in ms, not (just) the percentages (because a single ms can make a huge percentage difference).

    I just submitted each three times and get a different picture:

    mine: 10 ms (26%)    yours: 11 ms (18%)
    mine:  7 ms (90%)    yours:  8 ms (60%)
    mine:  9 ms (38%)    yours:  8 ms (60%)
    

    Far too unstable to draw a conclusion. I guess you submitted many more times?


  • 0
    S

    @StefanPochmann It is a beautiful solution. Will it be possible for you to explain the intuition behind result[i/c][i%c] ?


Log in to reply
 

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