519. Random Flip Matrix Medium

@problem@discussion
#Hash Table#Math#Reservoir Sampling#Randomized



1/**
2 * [519] Random Flip Matrix
3 *
4 * 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.
5 * 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.
6 * Implement the Solution class:
7 * 
8 * 	Solution(int m, int n) Initializes the object with the size of the binary matrix m and n.
9 * 	int[] flip() Returns a random index [i, j] of the matrix where matrix[i][j] == 0 and flips it to 1.
10 * 	void reset() Resets all the values of the matrix to be 0.
11 * 
12 *  
13 * Example 1:
14 * 
15 * Input
16 * ["Solution", "flip", "flip", "flip", "reset", "flip"]
17 * [[3, 1], [], [], [], [], []]
18 * Output
19 * [null, [1, 0], [2, 0], [0, 0], null, [2, 0]]
20 * Explanation
21 * Solution solution = new Solution(3, 1);
22 * solution.flip();  // return [1, 0], [0,0], [1,0], and [2,0] should be equally likely to be returned.
23 * solution.flip();  // return [2, 0], Since [1,0] was returned, [2,0] and [0,0]
24 * solution.flip();  // return [0, 0], Based on the previously returned indices, only [0,0] can be returned.
25 * solution.reset(); // All the values are reset to 0 and can be returned.
26 * solution.flip();  // return [2, 0], [0,0], [1,0], and [2,0] should be equally likely to be returned.
27 * 
28 *  
29 * Constraints:
30 * 
31 * 	1 <= m, n <= 10^4
32 * 	There will be at least one free cell for each call to flip.
33 * 	At most 1000 calls will be made to flip and reset.
34 * 
35 */
36pub struct Solution {}
37
38// problem: https://leetcode.com/problems/random-flip-matrix/
39// discuss: https://leetcode.com/problems/random-flip-matrix/discuss/?currentPage=1&orderBy=most_votes&query=
40
41// submission codes start here
42
43struct Solution {
44        vec![]
45    }
46
47
48/** 
49 * `&self` means the method takes an immutable reference.
50 * If you need a mutable reference, change it to `&mut self` instead.
51 */
52impl Solution {
53
54    fn new(m: i32, n: i32) -> Self {
55        
56    }
57    
58    fn flip(&self) -> Vec<i32> {
59        
60    }
61    
62    fn reset(&self) {
63        
64    }
65}
66
67/**
68 * Your Solution object will be instantiated and called as such:
69 * let obj = Solution::new(m, n);
70 * let ret_1: Vec<i32> = obj.flip();
71 * obj.reset();
72 */
73
74// submission codes end
75
76#[cfg(test)]
77mod tests {
78    use super::*;
79
80    #[test]
81    fn test_519() {
82    }
83}
84


Back
© 2025 bowen.ge All Rights Reserved.