LeetCode 如何不使用額外空間去更新二維數(shù)組

關(guān)于我的 Leetcode 題目解答喝峦,代碼前往 Github:https://github.com/chenxiangcyr/leetcode-answers


LeetCode題目:661 Image Smoother
Given a 2D integer matrix M representing the gray scale of an image, you need to design a smoother to make the gray scale of each cell becomes the average gray scale (rounding down) of all the 8 surrounding cells and itself. If a cell has less than 8 surrounding cells, then use as many as you can.
Example 1:

Input:
[[1,1,1],
[1,0,1],
[1,1,1]]
Output:
[[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
Explanation:
For the point (0,0), (0,2), (2,0), (2,2): floor(3/4) = floor(0.75) = 0
For the point (0,1), (1,0), (1,2), (2,1): floor(5/6) = floor(0.83333333) = 0
For the point (1,1): floor(8/9) = floor(0.88888889) = 0

Note:

  • The value in the given matrix is in the range of [0, 255].
  • The length and width of the given matrix are in the range of [1, 150].

分析:
題中看出數(shù)字的范圍是[0, 255]咱揍,一個整型是32位部宿,255只占用后8位。我們可以利用中間的8位來存儲計算結(jié)果,即00000000-00000000-計算結(jié)果-原始數(shù)據(jù)
對于一個數(shù)字A棉胀,獲得后8位,可以通過A&0xFF
對于一個數(shù)字A冀膝,將某個數(shù)字B存儲到A中間的8位唁奢,可以通過A = A | (B<<8)

完整代碼如下:

class Solution {
    public int[][] imageSmoother(int[][] M) {
        int rows = M.length;
        int columns = M[0].length;
        
        for(int i = 0; i < rows; i++) {
            for(int j = 0; j < columns; j++) {
                // 對于一個數(shù)字A,獲得后8位窝剖,可以通過A&0xFF
                int sum = M[i][j]&0xFF;
                int count = 1;
                
                // (i-1, j-1)
                if(i > 0 && j > 0) {
                    sum = sum + (M[i-1][j-1]&0xFF);
                    count++;
                }
                
                // (i-1, j)
                if(i > 0) {
                    sum = sum + (M[i-1][j]&0xFF);
                    count++;
                }
                
                // (i-1, j+1)
                if(i > 0 && j < columns - 1) {
                    sum = sum + (M[i-1][j+1]&0xFF);
                    count++;
                }
                
                // (i, j - 1)
                if(j > 0) {
                    sum = sum + (M[i][j-1]&0xFF);
                    count++;
                }
                
                // (i, j + 1)
                if(j < columns - 1) {
                    sum = sum + (M[i][j+1]&0xFF);
                    count++;
                }
                
                // (i+1, j-1)
                if(i < rows - 1 && j > 0) {
                    sum = sum + (M[i+1][j-1]&0xFF);
                    count++;
                }
                
                // (i+1, j)
                if(i < rows - 1) {
                    sum = sum + (M[i+1][j]&0xFF);
                    count++;
                }
                
                // (i+1, j+1)
                if(i < rows - 1 && j < columns - 1) {
                    sum = sum + (M[i+1][j+1]&0xFF);
                    count++;
                }
                
                // 對于一個數(shù)字A麻掸,將某個數(shù)字B存儲到A中間的8位,可以通過A = A | (B<<8)
                M[i][j] |= ((sum / count) << 8);
            }
        }
        
        for(int i = 0; i < rows; i++) {
            for(int j = 0; j < columns; j++) {
                M[i][j] >>= 8;
            }
        }
        
        return M;
    }
}

LeetCode題目:289. Game of Life
According to the Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970."

Given a board with m by n cells, each cell has an initial state live (1) or dead (0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):

  1. Any live cell with fewer than two live neighbors dies, as if caused by under-population.
  2. Any live cell with two or three live neighbors lives on to the next generation.
  3. Any live cell with more than three live neighbors dies, as if by over-population..
  4. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.

Write a function to compute the next state (after one update) of the board given its current state.

Follow up:

  1. Could you solve it in-place? Remember that the board needs to be updated at the same time: You cannot update some cells first and then use their updated values to update other cells.
  2. In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches the border of the array. How would you address these problems?

分析:
To solve it in place, we use 2 bits to store 2 states:

[2nd bit, 1st bit] = [next state, current state]

  • 00 dead (next) <- dead (current)
  • 01 dead (next) <- live (current)
  • 10 live (next) <- dead (current)
  • 11 live (next) <- live (current)

In the beginning, every cell is either 00 or 01.
Notice that 1st state is independent of 2nd state.
Imagine all cells are instantly changing from the 1st to the 2nd state, at the same time.
Let’s count # of neighbors from 1st state and set 2nd state bit.
Since every 2nd state is by default dead, no need to consider transition 01 -> 00.
In the end, delete every cell’s 1st state by doing >> 1.
For each cell’s 1st bit, check the 8 pixels around itself, and set the cell’s 2nd bit.

Transition 01 -> 11: when board == 1 and lives >= 2 && lives <= 3.
Transition 00 -> 10: when board == 0 and lives == 3.
To get the current state, simply do board[i][j] & 1
To get the next state, simply do board[i][j] >> 1
完整代碼如下:

public void gameOfLife(int[][] board) {
    if (board == null || board.length == 0) return;
    int m = board.length, n = board[0].length;

    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            int lives = liveNeighbors(board, m, n, i, j);

            // In the beginning, every 2nd bit is 0;
            // So we only need to care about when will the 2nd bit become 1.
            if (board[i][j] == 1 && lives >= 2 && lives <= 3) {  
                board[i][j] = 3; // Make the 2nd bit 1: 01 ---> 11
            }
            if (board[i][j] == 0 && lives == 3) {
                board[i][j] = 2; // Make the 2nd bit 1: 00 ---> 10
            }
        }
    }

    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            board[i][j] >>= 1;  // Get the 2nd state.
        }
    }
}

public int liveNeighbors(int[][] board, int m, int n, int i, int j) {
    int lives = 0;
    for (int x = Math.max(i - 1, 0); x <= Math.min(i + 1, m - 1); x++) {
        for (int y = Math.max(j - 1, 0); y <= Math.min(j + 1, n - 1); y++) {
            lives += board[x][y] & 1;
        }
    }
    lives -= board[i][j] & 1;
    return lives;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末赐纱,一起剝皮案震驚了整個濱河市脊奋,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌疙描,老刑警劉巖诚隙,帶你破解...
    沈念sama閱讀 219,589評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異淫痰,居然都是意外死亡最楷,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,615評論 3 396
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來籽孙,“玉大人烈评,你說我怎么就攤上這事》附ǎ” “怎么了讲冠?”我有些...
    開封第一講書人閱讀 165,933評論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長适瓦。 經(jīng)常有香客問我竿开,道長,這世上最難降的妖魔是什么玻熙? 我笑而不...
    開封第一講書人閱讀 58,976評論 1 295
  • 正文 為了忘掉前任否彩,我火速辦了婚禮,結(jié)果婚禮上嗦随,老公的妹妹穿的比我還像新娘列荔。我一直安慰自己,他們只是感情好枚尼,可當(dāng)我...
    茶點故事閱讀 67,999評論 6 393
  • 文/花漫 我一把揭開白布贴浙。 她就那樣靜靜地躺著,像睡著了一般署恍。 火紅的嫁衣襯著肌膚如雪崎溃。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,775評論 1 307
  • 那天盯质,我揣著相機(jī)與錄音袁串,去河邊找鬼。 笑死唤殴,一個胖子當(dāng)著我的面吹牛般婆,可吹牛的內(nèi)容都是我干的到腥。 我是一名探鬼主播朵逝,決...
    沈念sama閱讀 40,474評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼乡范!你這毒婦竟也來了配名?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,359評論 0 276
  • 序言:老撾萬榮一對情侶失蹤晋辆,失蹤者是張志新(化名)和其女友劉穎渠脉,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體瓶佳,經(jīng)...
    沈念sama閱讀 45,854評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡芋膘,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,007評論 3 338
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片为朋。...
    茶點故事閱讀 40,146評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡臂拓,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出习寸,到底是詐尸還是另有隱情胶惰,我是刑警寧澤,帶...
    沈念sama閱讀 35,826評論 5 346
  • 正文 年R本政府宣布霞溪,位于F島的核電站孵滞,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏鸯匹。R本人自食惡果不足惜坊饶,卻給世界環(huán)境...
    茶點故事閱讀 41,484評論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望殴蓬。 院中可真熱鬧幼东,春花似錦、人聲如沸科雳。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,029評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽糟秘。三九已至简逮,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間尿赚,已是汗流浹背散庶。 一陣腳步聲響...
    開封第一講書人閱讀 33,153評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留凌净,地道東北人悲龟。 一個月前我還...
    沈念sama閱讀 48,420評論 3 373
  • 正文 我出身青樓,卻偏偏與公主長得像冰寻,于是被迫代替她去往敵國和親须教。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,107評論 2 356

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