website/content/ChapterFour/0500~0599/0519.Random-Flip-Matrix.md
There is an m x n binary grid matrix with all the values set 0 initially. Design an algorithm to randomly pick an index (i, j) where matrix[i][j] == 0 and flips it to 1. All the indices (i, j) where matrix[i][j] == 0 should be equally likely to be returned.
Optimize your algorithm to minimize the number of calls made to the built-in random function of your language and optimize the time and space complexity.
Implement the Solution class:
Example 1:
Input
["Solution", "flip", "flip", "flip", "reset", "flip"]
[[3, 1], [], [], [], [], []]
Output
[null, [1, 0], [2, 0], [0, 0], null, [2, 0]]
Explanation
Solution solution = new Solution(3, 1);
solution.flip(); // return [1, 0], [0,0], [1,0], and [2,0] should be equally likely to be returned.
solution.flip(); // return [2, 0], Since [1,0] was returned, [2,0] and [0,0]
solution.flip(); // return [0, 0], Based on the previously returned indices, only [0,0] can be returned.
solution.reset(); // All the values are reset to 0 and can be returned.
solution.flip(); // return [2, 0], [0,0], [1,0], and [2,0] should be equally likely to be returned.
Constraints:
给你一个 m x n 的二元矩阵 matrix ,且所有值被初始化为 0 。请你设计一个算法,随机选取一个满足 matrix[i][j] == 0 的下标 (i, j) ,并将它的值变为 1 。所有满足 matrix[i][j] == 0 的下标 (i, j) 被选取的概率应当均等。
尽量最少调用内置的随机函数,并且优化时间和空间复杂度。
实现 Solution 类:
package leetcode
import "math/rand"
type Solution struct {
r int
c int
total int
mp map[int]int
}
func Constructor(m int, n int) Solution {
return Solution{
r: m,
c: n,
total: m * n,
mp: map[int]int{},
}
}
func (this *Solution) Flip() []int {
k := rand.Intn(this.total)
val := k
if v, ok := this.mp[k]; ok {
val = v
}
if _, ok := this.mp[this.total-1]; ok {
this.mp[k] = this.mp[this.total-1]
} else {
this.mp[k] = this.total - 1
}
delete(this.mp, this.total - 1)
this.total--
newR, newC := val/this.c, val%this.c
return []int{newR, newC}
}
func (this *Solution) Reset() {
this.total = this.r * this.c
this.mp = map[int]int{}
}