519. Random Flip Matrix

1. Question

There is an m x n binary grid matrix with all the values set 0 initially. Design an algorithm to randomly pick an index (i, j) where matrix[i][j] == 0 and flips it to 1. All the indices (i, j) where matrix[i][j] == 0 should be equally likely to be returned.

Optimize your algorithm to minimize the number of calls made to the built-in random function of your language and optimize the time and space complexity.

Implement the Solution class:

  • Solution(int m, int n)Initializes the object with the size of the binary matrix m and n.
  • int[] flip() Returns a random index [i, j] of the matrix where matrix[i][j] == 0 and flips it to 1.

  • void reset() Resets all the values of the matrix to be 0.

2. Examples

Example 1:

Input
["Solution", "flip", "flip", "flip", "reset", "flip"]
[[3, 1], [], [], [], [], []]
Output
[null, [1, 0], [2, 0], [0, 0], null, [2, 0]]

Explanation
Solution solution = new Solution(3, 1);
solution.flip();  // return [1, 0], [0,0], [1,0], and [2,0] should be equally likely to be returned.
solution.flip();  // return [2, 0], Since [1,0] was returned, [2,0] and [0,0]
solution.flip();  // return [0, 0], Based on the previously returned indices, only [0,0] can be returned.
solution.reset(); // All the values are reset to 0 and can be returned.
solution.flip();  // return [2, 0], [0,0], [1,0], and [2,0] should be equally likely to be returned.

3. Constraints

  • 1 <= m, n <= 104
  • There will be at least one free cell for each call to flip.
  • At most 1000 calls will be made to flip and reset.

4. References

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/random-flip-matrix 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

5. Solutions

class Solution {
  int m;
  int n;
  int total;
  Set<Integer> set = new HashSet<>();
  Random random = new Random();

  public Solution(int m, int n) {
    this.m = m;
    this.n = n;
    this.total = m * n;
    reset();
  }

  public int[] flip() {
    int a = random.nextInt(total);
    while(set.contains(a)) {
      a = random.nextInt(total);
    }
    set.add(a);
    return new int[]{a / n, a % n};
  }

  public void reset() {
    set.clear();
  }
}

/**
 * Your Solution object will be instantiated and called as such:
 * Solution obj = new Solution(m, n);
 * int[] param_1 = obj.flip();
 * obj.reset();
 */
Copyright © rootwhois.cn 2021-2022 all right reserved,powered by GitbookFile Modify: 2022-11-26 20:03:31

results matching ""

    No results matching ""