566. Reshape the Matrix

public class Solution {
    public int[][] matrixReshape(int[][] nums, int r, int c) {
        ArrayList<Integer> li=new ArrayList<Integer>();
        int i=0,j=0,count=0;
        if((nums.length*nums[0].length)!=(r*c))return nums;
        for(;i<nums.length;i++){
            for(j=0;j<nums[0].length;j++){
                li.add(nums[i][j]);
            }
        }
        int[][] res=new int[r][c];
    
        for(i=0;i<r;i++){
            for(j=0;j<c;j++){
                res[i][j]=li.get(count++);
            }
        }
        return res;
    }
}

太蠢了,人家只用一次循环就搞定了。

public class Solution {
    public int[][] matrixReshape(int[][] nums, int r, int c) {
      
        int row = nums.length;
        int col = nums[0].length;
        int [][] result = new int[r][c];
        
        if (r*c!=row*col){
            return nums;
        }
        int n=0, m=0;
        for (int i=0; i<row; i++){
            for (int j=0; j<col; j++){
                result[n][m]=nums[i][j];
                m++;
                    
                if (m==c){
                    m=0;
                    n++;
                }
                
              }
        }
            
        return result;
        }
   
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容