[leetcode]566. Reshape the Matrix

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.

Example1:
Input:
nums =
[[1,2],
[3,4]]
r = 1, c = 4
Output:
[[1,2,3,4]]
Explanation:
The row-traversing of nums is [1,2,3,4]. The new reshaped matrix is a 1 * 4 matrix, fill it row by row by using the previous list.

Example2:
Input:
nums =
[[1,2],
[3,4]]
r = 2, c = 4
Output:
[[1,2],
[3,4]]
Explanation:
There is no way to reshape a 2 * 2 matrix to a 2 * 4 matrix. So output the original matrix.

Note
1.The height and width of the given matrix is in range [1, 100].
2.The given r and c are all positive.

思路
思路很簡單啊,就是把二維數組捋直變成一維的,再按照新二維數組的要求放進去。

問題
但是我這個垃圾被卡了四天,因為我讀不懂題目。我就是沒看明白這個** columnSizes和* returnSize是來干嘛的有什么用,現在即使accepted了我也不懂,當然最后也還是根據discuss修改了才成功的。按注釋里的意思應該是返回一個包含* returnSize個數組的數組,即* returnSize應該是行值,并且這些數組的大小被返回成 * columnSizes數組(所以說不就是c嘛,每個數組都是c啊)。
并且看到二級指針很懵,看了蠻久二級指針和數組指針相關的東西,指針確實是難orz。感覺把columnSizes作為二級指針應該是要對主函數中的指針做修改,單純傳一級指針無法做到只能是傳遞二級指針,這樣?
如何用二級指針建立二位數據并賦值確實是第一次接觸。
第一次submit報錯runtime error,應該是數組越界或者指針越界的問題,好吧這個點了我也忘了當時是改的哪里了,好像是 p[count]=nums[i][j]這里,我一開始寫的是nums[i*numsColSize+j],但是按道理子函數中以二級指針形式傳入的二維數組不是不可以用a[][]的形式使用的嘛?另外根據discuss里解答應該是題目默認不能直接返回sums(好像是根據注釋里的意思?不然我實在不太懂后兩個參數有什么用),if判斷賦值參考了discuss進行了修改。
然后這道題充滿疑問的accepted了。

代碼

/**
 * Return an array of arrays of size *returnSize.
 * The sizes of the arrays are returned as *columnSizes array.
 * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
 */
int** matrixReshape(int** nums, int numsRowSize, int numsColSize, int r, int c, int** columnSizes, int* returnSize) {
    int *p;
    p=(int *)malloc(sizeof(int)*r*c);
    int count=0;
    int count2=0;
    int m,n;
    int **a,i,j;
    a = (int**)malloc(r*sizeof(int*));
    *columnSizes=(int*)malloc(r*sizeof(int));
    *returnSize=r;

    if (r * c != numsColSize * numsRowSize) {
        r = numsRowSize;
        c = numsColSize;
    }
    for(i=0;i<numsRowSize;i++){
        for(j=0;j<numsColSize;j++){
        p[count]=nums[i][j];
        count++;         
        }
    }
    for(m=0;m<r;m++){
        a[m] = (int*)malloc(c*sizeof(int));
        (*columnSizes)[m]=c;
        for(n=0;n<c;n++){
        a[m][n]=p[count2];
        count2++;
        }
     }
     return a; 
}

寫一半出去玩了,好了,也算是今日事今日畢了。

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容