leetcode519. 随机翻转矩阵


力扣链接

题目描述

给你一个 m x n 的二元矩阵 matrix ,且所有值被初始化为 0 。请你设计一个算法,随机选取一个满足 matrix[i][j] == 0 的下标 (i, j) ,并将它的值变为 1 。所有满足 matrix[i][j] == 0 的下标 (i, j) 被选取的概率应当均等。

尽量最少调用内置的随机函数,并且优化时间和空间复杂度。

实现 Solution 类:

  • Solution(int m, int n) 使用二元矩阵的大小 mn 初始化该对象
  • int[] flip() 返回一个满足 matrix[i][j] == 0 的随机下标 [i, j] ,并将其对应格子中的值变为 1
  • void reset() 将矩阵中所有的值重置为 0

示例:

输入
["Solution", "flip", "flip", "flip", "reset", "flip"]
[[3, 1], [], [], [], [], []]
输出
[null, [1, 0], [2, 0], [0, 0], null, [2, 0]]

解释
Solution solution = new Solution(3, 1);
solution.flip();  // 返回 [1, 0],此时返回 [0,0]、[1,0] 和 [2,0] 的概率应当相同
solution.flip();  // 返回 [2, 0],因为 [1,0] 已经返回过了,此时返回 [2,0] 和 [0,0] 的概率应当相同
solution.flip();  // 返回 [0, 0],根据前面已经返回过的下标,此时只能返回 [0,0]
solution.reset(); // 所有值都重置为 0 ,并可以再次选择下标返回
solution.flip();  // 返回 [2, 0],此时返回 [0,0]、[1,0] 和 [2,0] 的概率应当相同

提示:

  • 1 <= m, n <= 104
  • 每次调用flip 时,矩阵中至少存在一个值为 0 的格子。
  • 最多调用 1000flipreset 方法。

解题思路-数组映射

题解链接

代码

class Solution {
    
    
    int m;
    int n;
    Map<Integer, Integer> map;
    Random random;
    int total;

    public Solution(int m, int n) {
    
    
       map = new HashMap<>();
       random = new Random();
       this.m = m;
       this.n = n;
       this.total = m * n;
    }
    
    public int[] flip() {
    
    
       int x = random.nextInt(total);
       total--;
       int idx = map.getOrDefault(x, x);
       map.put(x, map.getOrDefault(total, total));
       return new int[]{
    
    idx / n, idx % n};
    }

    public void reset() {
    
    
        total = m * n;
        map.clear();
    }
}


时间复杂度

  • 时间复杂度:flip() 操作的时间复杂度为 O(1),reset() 操作的时间复杂度为 O(F),其中 F 是在上一次 reset() 之后执行 flip() 的次数。

  • 空间复杂度:O(F),其中 FF 代表执行函数 flip() 的次数。

猜你喜欢

转载自blog.csdn.net/qq_43478625/article/details/121576432