[LeetCode] 519. Random Flip Matrix 隨機翻轉矩陣


 

You are given the number of rows n_rows and number of columns n_cols of a 2D binary matrix where all values are initially 0. Write a function flip which chooses a 0 value uniformly at random, changes it to 1, and then returns the position [row.id, col.id] of that value. Also, write a function reset which sets all values back to 0. Try to minimize the number of calls to system's Math.random() and optimize the time and space complexity.

Note:

  1. 1 <= n_rows, n_cols <= 10000
  2. 0 <= row.id < n_rows and 0 <= col.id < n_cols
  3. flip will not be called when the matrix has no 0 values left.
  4. the total number of calls to flip and reset will not exceed 1000.

Example 1:

Input: 
["Solution","flip","flip","flip","flip"]
[[2,3],[],[],[],[]] Output: [null,[0,1],[1,2],[1,0],[1,1]] 

Example 2:

Input: 
["Solution","flip","flip","reset","flip"]
[[1,2],[],[],[],[]] Output: [null,[0,0],[0,1],null,[0,0]]

Explanation of Input Syntax:

The input is two lists: the subroutines called and their arguments. Solution's constructor has two arguments, n_rows and n_colsflip and resethave no arguments. Arguments are always wrapped with a list, even if there aren't any.

 

這道題讓我們隨機翻轉矩陣中的一個位置,由於之前連續做了好幾道隨機選點的題 Implement Rand10() Using Rand7()Generate Random Point in a Circle,和 Random Point in Non-overlapping Rectangles。以為這道題也要用拒絕采樣 Rejection Sampling 來做,其實不是的。這道題給了一個矩形的長和寬,讓每次隨機翻轉其中的一個點,其中的隱含條件是,之前翻轉過的點,下一次不能再翻轉回來,而隨機生成點是有可能有重復的,一旦很多點都被翻轉后,很大概率會重復生成之前的點,所以需要有去重復的操作,而這也是本題的難點所在。博主最先的想法是,既然有可能生成重復的點,那么使用一個 while 循環,只要生成了之前的點,就重新再生成一個,這么一說,感覺又有點像拒絕采樣 Rejection Sampling 的原理了。不管了,不管黑貓白貓,能抓耗子🐭的就是好貓🐱。題目中說了盡量減少空間使用度,就不能生成整個二維數組了,可以用一個 HashSet 來記錄翻轉過了點,這樣也方便進行查重操作。所以每次都隨機出一個長和寬,然后看這個點是否已經在 HashSe t中了,不在的話,就加入 HashSet,然后返回即可,參見代碼如下:

 

解法一:

class Solution {
public:
    Solution(int n_rows, int n_cols) {
        row = n_rows; col = n_cols;
    }
    
    vector<int> flip() {
        while (true) {
            int x = rand() % row, y = rand() % col;
            if (!flipped.count(x * col + y)) {
                flipped.insert(x * col + y);
                return {x, y};
            }
        }
    }
    
    void reset() {
        flipped.clear();
    }

private:
    int row, col;
    unordered_set<int> flipped;
};

 

由於題目中讓我們盡量少用 rand() 函數,所以可以進行優化一樣,不在同時生成兩個隨機數,而是只生成一個,然后拆分出長和寬即可,其他部分和上面均相同,參見代碼如下:

 

解法二:

class Solution {
public:
    Solution(int n_rows, int n_cols) {
        row = n_rows; col = n_cols;
    }
    
    vector<int> flip() {
        while (true) {
            int val = rand() % (row * col);
            if (!flipped.count(val)) {
                flipped.insert(val);
                return {val / col, val % col};
            }
        }
    }
    
    void reset() {
        flipped.clear();
    }

private:
    int row, col;
    unordered_set<int> flipped;
};

 

其實我們還可以進一步的優化 rand() 的調用數,可以讓每個 flip() 函數只調用一次 rand() 函數,這該怎么做呢,這里就有一些 trick 了。需要使用一個變量 size,初始化為矩形的長乘以寬,然后還是只生成一個隨機數id,並使用另一個變量 val 來記錄它。接下來給 size 自減1,由於 rand() % size 得到的隨機數的范圍是 [0, size-1],那么假如第一次隨機出了 size-1 后,此時 size 自減1之后,下一次不必擔心還會隨機出 size-1,因為此時的 size 比之前減少了1。如果第一次隨機出了0,假設最開始 size=4,那么此時自減1之后,size=3,此時將0映射到3。那么下次如果再次隨機出了0,此時 size 自減1之后,size=2,現在0有映射值,所以將 id 改為其映射值3,然后再將0映射到2,這樣下次就算再搖出了0,還可以改變id值。大家有沒有發現,映射值都是沒有沒使用過的數字,這也是為啥開始先檢測 id 是否被使用了,若已經被使用了,則換成其映射值,然后再更新之前的 id 的映射值,找到下一個未被使用的值即可,參見代碼如下:

 

解法三:

class Solution {
public:
    Solution(int n_rows, int n_cols) {
        row = n_rows; col = n_cols;
        size = row * col;
    }
    
    vector<int> flip() {
        int id = rand() % size, val = id;
        --size;
        if (m.count(id)) id = m[id];
        m[val] = m.count(size) ? m[size] : size;
        return {id / col, id % col};
    }
    
    void reset() {
        m.clear();
        size = row * col;
    }

private:
    int row, col, size;
    unordered_map<int, int> m;
};

 

Github 同步地址:

https://github.com/grandyang/leetcode/issues/519

 

參考資料:

https://leetcode.com/problems/random-flip-matrix/

https://leetcode.com/problems/random-flip-matrix/discuss/177809/c%2B%2B-solution

https://leetcode.com/problems/random-flip-matrix/discuss/154053/Java-AC-Solution-call-Least-times-of-Random.nextInt()-function

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM