-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathflip_matrix.txt
44 lines (38 loc) · 1.15 KB
/
flip_matrix.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
519. Random Flip Matrix
/*
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:
Solution(int m, int n) Initializes the object with the size of the binary matrix m and n.
int[] flip() Returns a random index [i, j] of the matrix where matrix[i][j] == 0 and flips it to 1.
void reset() Resets all the values of the matrix to be 0.
*\
class Solution {
public:
int m,n;
int i = 0, j = 0;
Solution(int m, int n) {
this -> m = m;
this -> n = n;
}
vector<int> flip() {
int I = i , J = j;
if(j + 1 < n){
j++;
}
else if(i + 1 < m){
i++;
j = 0;
}
else{
i = 0;
j = 0;
}
return {I,J};
}
void reset() {
}
};