519 Random Flip Matrix
519. Random Flip Matrix
1. Question
You are given the number of rowsn_rows
and number of columnsn_cols
of a 2D binary matrix where all values are initially 0. Write a functionflip
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 functionreset
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 <= n_rows, n_cols <= 10000
0 <= row.id < n_rows
and0 <= col.id < n_cols
flip
will not be called when the matrix has no 0 values left.the total number of calls to
flip
andreset
will not exceed 1000.
Example 1:
Example 2:
Explanation of Input Syntax:
The input is two lists: the subroutines called and their arguments.Solution
's constructor has two arguments,n_rows
andn_cols
. flip
andreset
have no arguments. Arguments are always wrapped with a list, even if there aren't any.
2. Implementation
(1) Fisher-Yate 算法
3. Time & Space Complexity
Fisher-Yate 时间复杂度flip: O(1), 空间复杂度O(m * n), 空间主要是map,m为行,n为列
Last updated
Was this helpful?