File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
#include<vector>
2+
#include<algorithm>
3+
#include<iostream>
4+
#include<unordered_map>
5+
using namespace std;
6+
7+
class Solution {
8+
int r, c, k; // r: 矩阵的行数, c: 列数, k: 矩阵中元素的个数
9+
unordered_map<int, int> dict; // 大脑中构建一个映射: x -> x, 默认用这个映射, 将不满足这个映射的特殊键值对存入哈希表
10+
public:
11+
Solution(int m, int n) {
12+
r = m;
13+
c = n;
14+
k = r*c;
15+
}
16+
17+
vector<int> flip() { /* 先把矩阵(二维数组)拉平成1维数组, 再进行随机处理 */
18+
int key = rand() % k;
19+
int val = key; // 默认的映射规则: x -> x (x的范围是: 0 -> k-1)
20+
if (dict.count(key))
21+
val = dict[key];
22+
23+
if (!dict.count(k - 1))
24+
dict[k-1] = k - 1;
25+
// 当key处的kvp用过后, 用最后一个kvp(key = k-1)覆盖之, 然后删掉最后一个kvp, 就可以在剩下的数中实现随机化选择
26+
dict[key] = dict[k-1];
27+
dict.erase(k - 1);
28+
k--; // 表示删掉了末尾的一个数
29+
30+
int newRow = val / c;
31+
int newCol = val % c;
32+
return {newRow, newCol};
33+
}
34+
35+
void reset() {
36+
k = r*c;
37+
dict.clear();
38+
}
39+
};
40+
41+
// Test
42+
int main()
43+
{
44+
int m = 3;
45+
int n = 1;
46+
Solution* sol = new Solution(m, n);
47+
vector<int> res = sol->flip();
48+
cout << "{" << res[0] << ", " << res[1] << "}" << endl;
49+
res = sol->flip();
50+
cout << "{" << res[0] << ", " << res[1] << "}" << endl;
51+
res = sol->flip();
52+
cout << "{" << res[0] << ", " << res[1] << "}" << endl;
53+
sol->reset();
54+
res = sol->flip();
55+
cout << "{" << res[0] << ", " << res[1] << "}" << endl;
56+
57+
cout << "OK~" << endl;
58+
59+
return 0;
60+
}
File renamed without changes.

0 commit comments

Comments
 (0)