鏈接: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%的用戶