forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain4.cpp
65 lines (48 loc) · 1.22 KB
/
main4.cpp
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/// Source : https://leetcode.com/problems/random-flip-matrix/description/
/// Author : liuyubobobo
/// Time : 2018-08-28
#include <iostream>
#include <vector>
#include <unordered_map>
#include <cassert>
using namespace std;
/// Position redirection
/// Time Complexty: O(1)
/// Space Complexity: O(min(len(call of flip), m*n))
class Solution {
private:
int m, n;
int left;
unordered_map<int, int> redirection;
public:
Solution(int n_rows, int n_cols): m(n_rows), n(n_cols) {
reset();
}
vector<int> flip() {
int randNum = rand() % left;
left --;
int ret = randNum;
if(redirection.find(randNum) != redirection.end())
ret = redirection[randNum];
if(redirection.find(left) == redirection.end())
redirection[randNum] = left;
else
redirection[randNum] = redirection[left];
return {ret / n, ret % n};
}
void reset() {
left = m * n;
redirection.clear();
}
};
void print_vec(const vector<int>& vec){
for(int e: vec)
cout << e << " ";
cout << endl;
}
int main() {
Solution solution(2, 2);
for(int i = 0; i < 4; i ++)
print_vec(solution.flip());
return 0;
}