-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrandomFlipMatrix.cpp
More file actions
39 lines (33 loc) · 832 Bytes
/
randomFlipMatrix.cpp
File metadata and controls
39 lines (33 loc) · 832 Bytes
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
// Source: https://leetcode.com/problems/random-flip-matrix/
// Author: Miao Zhang
// Date: 2021-02-19
class Solution {
public:
Solution(int n_rows, int n_cols): rows_(n_rows),
cols_(n_cols), n_(n_rows * n_cols) {
}
vector<int> flip() {
int s = rand() % (n_--);
int index = s;
if (dic_.count(s)) {
index = dic_[s];
}
dic_[s] = dic_.count(n_) ? dic_[n_] : n_;
return {index / cols_, index % cols_};
}
void reset() {
dic_.clear();
n_ = rows_ * cols_;
}
private:
int rows_;
int cols_;
int n_;
unordered_map<int, int> dic_;
};
/**
* Your Solution object will be instantiated and called as such:
* Solution* obj = new Solution(n_rows, n_cols);
* vector<int> param_1 = obj->flip();
* obj->reset();
*/