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.

分析

這道題讓我們實現(xiàn)矩陣大小的重塑。
答題思路: 對于這種二維數(shù)組大小重新分配的問題的關(guān)鍵就是對應(yīng)位置的坐標(biāo)轉(zhuǎn)換,最直接的辦法就是把原數(shù)組拉直胸梆,變成一條直線念恍,然后再組成新數(shù)組话原。

解法1

這道題我們先判斷給定數(shù)組是否能重塑成給定的大小绍豁,就是看兩者的元素個數(shù)是否相同,直接行數(shù)乘以列數(shù)即可通贞,然后我們重建一個目標(biāo)大小的數(shù)組焊夸,并開始遍歷仁连,對于每個位置,我們先轉(zhuǎn)為拉之后的一維坐標(biāo)阱穗,然后在算出在原數(shù)組中的對應(yīng)位置復(fù)制過來即可饭冬,代碼如下:

C++

class Solution {
public:
    vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
        int m = nums.size(), n = nums[0].size();
        if (m * n != r * c) return nums;
        vector<vector<int>> res(r, vector<int>(c));
        for (int i = 0; i < r; i++) {
            for (int j = 0; j < c; j++) {
                int k = i * c + j;
                res[i][j] = nums[k / n][k % n];
            }
        }
        return res;
    }
};

Swift

func matrixReshape(_ nums: [[Int]], _ r: Int, _ c: Int) -> [[Int]] {
    let m = nums.count, n = nums[0].count
    if (m * n != r * c) { return nums }
    var res = [[Int]](repeating: [Int](repeating: 0, count: c), count: r)
    for i in 0..<r {
        for j in 0..<c {
            let k = i * c + j
            res[i][j] = nums[k / n][k % n]
        }
    }
    return res
}
print(matrixReshape([[1, 2], [3, 4]], 1, 4))

解法2

下面這種方法整體思路和上面沒啥區(qū)別,但是只使用了一個循環(huán)揪阶,直接就是遍歷拉直后的一維數(shù)組的坐標(biāo)昌抠,然后分別轉(zhuǎn)換為兩個二維數(shù)組的坐標(biāo)進行賦值,參見代碼如下:

C++

class Solution {
public:
    vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
        int m = nums.size(), n = nums[0].size();
        if (m * n != r * c) return nums;
        vector<vector<int>> res(r, vector<int>(c));
        for (int i = 0; i < r * c; i++) {
            res[i / c][i % c] = nums[i / n][i % n];
        }
        return res;
    }
};

Swift

func matrixReshape(_ nums: [[Int]], _ r: Int, _ c: Int) -> [[Int]] {
    let m = nums.count, n = nums[0].count
    if (m * n != r * c) { return nums }
    var res = [[Int]](repeating: [Int](repeating: 0, count: c), count: r)
    for i in 0..<r*c {
        res[i / c][i % c] = nums[i / n][i % n]
    }
    return res
}
print(matrixReshape([[1, 2], [3, 4]], 1, 4))
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末鲁僚,一起剝皮案震驚了整個濱河市炊苫,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌冰沙,老刑警劉巖侨艾,帶你破解...
    沈念sama閱讀 222,104評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異拓挥,居然都是意外死亡蒋畜,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,816評論 3 399
  • 文/潘曉璐 我一進店門撞叽,熙熙樓的掌柜王于貴愁眉苦臉地迎上來姻成,“玉大人,你說我怎么就攤上這事愿棋】普梗” “怎么了?”我有些...
    開封第一講書人閱讀 168,697評論 0 360
  • 文/不壞的土叔 我叫張陵糠雨,是天一觀的道長才睹。 經(jīng)常有香客問我,道長甘邀,這世上最難降的妖魔是什么琅攘? 我笑而不...
    開封第一講書人閱讀 59,836評論 1 298
  • 正文 為了忘掉前任,我火速辦了婚禮松邪,結(jié)果婚禮上坞琴,老公的妹妹穿的比我還像新娘。我一直安慰自己逗抑,他們只是感情好剧辐,可當(dāng)我...
    茶點故事閱讀 68,851評論 6 397
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著邮府,像睡著了一般荧关。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上褂傀,一...
    開封第一講書人閱讀 52,441評論 1 310
  • 那天忍啤,我揣著相機與錄音,去河邊找鬼仙辟。 笑死同波,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的欺嗤。 我是一名探鬼主播参萄,決...
    沈念sama閱讀 40,992評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼煎饼!你這毒婦竟也來了讹挎?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,899評論 0 276
  • 序言:老撾萬榮一對情侶失蹤吆玖,失蹤者是張志新(化名)和其女友劉穎筒溃,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體沾乘,經(jīng)...
    沈念sama閱讀 46,457評論 1 318
  • 正文 獨居荒郊野嶺守林人離奇死亡怜奖,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,529評論 3 341
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了翅阵。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片歪玲。...
    茶點故事閱讀 40,664評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡迁央,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出滥崩,到底是詐尸還是另有隱情岖圈,我是刑警寧澤,帶...
    沈念sama閱讀 36,346評論 5 350
  • 正文 年R本政府宣布钙皮,位于F島的核電站蜂科,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏短条。R本人自食惡果不足惜导匣,卻給世界環(huán)境...
    茶點故事閱讀 42,025評論 3 334
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望茸时。 院中可真熱鬧贡定,春花似錦、人聲如沸屹蚊。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,511評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽汹粤。三九已至命斧,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間嘱兼,已是汗流浹背国葬。 一陣腳步聲響...
    開封第一講書人閱讀 33,611評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留芹壕,地道東北人汇四。 一個月前我還...
    沈念sama閱讀 49,081評論 3 377
  • 正文 我出身青樓,卻偏偏與公主長得像踢涌,于是被迫代替她去往敵國和親通孽。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,675評論 2 359

推薦閱讀更多精彩內(nèi)容