566. Reshape the Matrix

In MATLAB, there is a very useful function called 'reshape', which can reshape a matrix into a new one with different size but keep its original data.

You're given a matrix represented by a two-dimensional array, and two positive integers r and c representing the row number and column number of the wanted reshaped matrix, respectively.

The reshaped matrix need to be filled with all the elements of the original matrix in the same row-traversing order as they were.

If the 'reshape' operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.

我使用整個長度來變換訪問兩個數組的下標,公式是i*col+j+1=count。
但是我在重新映射到result數組時,發生了錯誤。使用了index1=count/col來訪問i。當j=col-1時使用這個公式的話,明顯的并不能得到我想要的I,例如對于一個2x2的矩陣,當J=1時明顯的count=2,那么count/2=1,但是此時明顯的I=0,根源在于我為了計算count對j進行了加一處理,但這個處理在進行得index1操作時會對I有影響

class Solution {
    public int[][] matrixReshape(int[][] nums, int r, int c) {
        int row =nums.length;
        int col =nums[0].length;
        if(r*c!=row*col)
            return nums;
        int[][] result = new int[r][c];
        for(int i = 0 ;i<row;i++)
        {
            for(int j = 0;j<col;j++)
            {
                int count =i*col+j+1;
                int index1=  (count-1)/c ;
                int index2=  (count-1)%c;
                result[index1][index2]=nums[i][j];
            }
        
        }
        return result;
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 背景 一年多以前我在知乎上答了有關LeetCode的問題, 分享了一些自己做題目的經驗。 張土汪:刷leetcod...
    土汪閱讀 12,769評論 0 33
  • 近三個月的時間沒有看電影了,雖然之前就被和菜頭種草了《血戰鋼鋸嶺》,但是一直拖到了影片下線后,總算是在一個周末,抱...
    波米諾不知道閱讀 159評論 0 0
  • 暢游雁蕩山后直達寧波。 寧波,簡稱甬,副省級市、計劃單列市,世界第四大港口城市。 百度介紹:寧波著名景點有天一閣、...
    平安是福笑囗常開閱讀 1,417評論 0 1