LeetCode每日一题:519. 随机翻转矩阵【2021/11/27】

162 阅读1分钟

题目链接:519. 随机翻转矩阵 - 力扣(LeetCode) (leetcode-cn.com)

难度:Medium

题目等价于从 00 ~ nm n*m 中随机选一个没有选择过的值,暴力 rand()rand() 即可。

unordered_mapunordered\_map 记录某个值是否被选择过,unordered_mapunordered\_map 是基于哈希的,效率应该更高一点。

class Solution {
    unordered_map<int,int>mp;
    int n,m;
    int len;
public:
    Solution(int m, int n) {
        this->m = m;
        this->n = n;
        this->len = n*m;
    }
    
    vector<int> flip() {
        while(1){
            int rnd = rand() % len;
            if(!mp[rnd]){
                mp[rnd] = 1;
                return { rnd/this->n, rnd%this->n};
            }
        }
        return {};
    }
    
    void reset() {
    mp.clear();
    }
};