LeetCode - 519. Random Flip Matrix

鏈接:https://leetcode-cn.com/problems/random-flip-matrix/
難度:medium

隨機翻轉(zhuǎn)二維數(shù)組,其實并不一定需要構(gòu)造二維數(shù)組。


class Solution {

    static Random ran = new Random(System.currentTimeMillis());
    Set<Integer> matrix;
    int m;
    int n;

    public Solution(int m, int n) {
        this.matrix = new HashSet<Integer>();
        this.m = m;
        this.n = n;
    }
    
    public int[] flip() {
        Integer idx;
        while(matrix.contains(idx = ran.nextInt(m * n)));
        matrix.add(idx);
        return new int[] {idx / n, idx % n};
    }
    
    public void reset() {
        this.matrix = new HashSet<Integer>();
    }

}

/**
 * Your Solution object will be instantiated and called as such:
 * Solution obj = new Solution(m, n);
 * int[] param_1 = obj.flip();
 * obj.reset();
 */

其實感覺以上解法的隨機并不是真正平均概率的隨機。真正的隨機,應(yīng)該剔除掉flip之后的數(shù)字賦予相同概率,但那樣做可能就至少要O(n)了感覺。罷了罷了,AC了下一道。。

執(zhí)行用時:38 ms, 在所有 Java 提交中擊敗了12.50%的用戶
內(nèi)存消耗:38.8 MB, 在所有 Java 提交中擊敗了96.43%的用戶

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容