Java Concise O(nm) time


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

  • 1

    why cannot use k=r*i+j? I think it is equivalent to k++ for ever loop. However, it shows that index out of bounds.


  • -4
    M

    @compton_scatter
    Isn't it supposed to be
    if (r*c != n+m) return nums;


  • 0
    D

    If i,j are both negative, there will be problems......


  • -4
    L

    I don't know why, but the runtime of your code is actually slow
    Now I know why, Because I' submit this from mainland China!
    Fuck GFW


  • 0

    Python version

    class Solution(object):
        def matrixReshape(self, nums, r, c):
            row, col = len(nums), len(nums[0])
            res = [[None] * c for _ in xrange(r)]
            if row*col != r*c:
                return nums
            else:
                for i in range(r*c):
                    res[i//c][i%c]=nums[i//col][i%col]
                return res
    

  • -3
    L

    public int[][] matrixReshape(int[][] nums, int r, int c) {
    int newNums[] = null;
    int mp[][]=null;
    int len=0;
    int index=0;
    for(int i=0;i<nums.length;i++){
    len+=nums[i].length;
    }
    newNums=new int [len];
    for(int i=0;i<nums.length;i++){
    for(int j=0;j<nums[i].length;j++){
    newNums[index++]=nums[i][j];
    }
    }
    int z=0;
    int m=rc;
    int firstLength=nums.length;
    int secondLength=nums[0].length;
    if(firstLength
    secondLength==m){
    mp=new int[r][c];
    for(int i=0;i<r;i++){
    for(int j=0;j<c;j++){
    mp[i][j]=newNums[z++];
    }
    }

    		return mp;
    	}	
    	return nums;
    

    }

    //my runtime beats 43.55 % of java submissions


  • 0
    class Solution {
        public int[][] matrixReshape(int[][] nums, int r, int c) {
            
            int[][] res = new int[r][c];
            if(nums.length == 0 || nums.length * nums[0].length != r * c) return nums;
            int i = 0;
            for(int[] row: nums){
              for(int n: row){
                res[i / c][i % c] = n;
                i++;
              }
            }
            return res;
        }
    }

Log in to reply
 

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