[LeetCode] Random Flip Matrix 随机翻转矩阵

时间:2023-12-25 18:36:49

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 的原理了。不管了,不管黑猫白猫,能抓耗子