假设我们有一个二进制矩阵,行数为n_rows,列数为n_cols。这里所有的值最初都是0。我们必须定义一个函数flip(),该函数随机地均匀选择0值,将其更改为1,然后返回该值的位置[row.id,col.id]。同样,我们必须编写另一个函数reset(),将所有值都设置为0。我们必须尝试最小化对系统Math.random()的调用次数,并优化时间和空间复杂度。
如果我们具有2x3阶矩阵,并且调用四次翻转,则结果将为[0,1],[1,2],[1,0],[1,1]。
让我们看下面的实现以更好地理解-#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<int> v){
cout << "[";
for(int i = 0; i<v.size(); i++){
cout << v[i] << ", ";
}
cout << "]"<<endl;
}
class Solution {
public:
unordered_map <int, int> holes;
int n;
int m;
int size;
Solution(int n_rows, int n_cols) {
srand(time(NULL));
n = n_rows;
m = n_cols;
size = n * m;
}
vector<int> flip() {
int id = rand() % size;
size--;
int rid = id;
if(holes.count(id)){
id = holes[id];
}
holes[rid] = holes.count(size) ? holes[size] : size;
return {id / m, id % m};
}
void reset() {
size = n * m;
holes.clear();
}
};
main(){
Solution ob(2,2);
print_vector(ob.flip());
print_vector(ob.flip());
print_vector(ob.flip());
print_vector(ob.flip());
}初始化构造函数使用 2,2 以及调用 flip4次
输出结果
[1, 1, ] [0, 0, ] [1, 0, ] [0, 1, ]