程式語言 - LeetCode - C++ - 519. Random Flip Matrix



參考資訊:
https://ithelp.ithome.com.tw/articles/10337601

題目:


解答:

class Solution {
private:
    int m;
    int n;
    int remain;
    unordered_map<int, int> mp;

public:
    Solution(int m, int n) {
        this->m = m;
        this->n = n;
        remain = m * n;
    }
    
    vector<int> flip() {
        int r = rand() % remain--;
        int x =  mp.count(r) ? mp[r] : r;
        mp[r] = mp.count(remain) ? mp[remain] : remain;

        return { x / n, x % n };
    }
    
    void reset() {
        mp.clear();
        remain = m * n;
    }
};

/**
 * Your Solution object will be instantiated and called as such:
 * Solution* obj = new Solution(m, n);
 * vector<int> param_1 = obj->flip();
 * obj->reset();
 */