Leetcode每日一题——随机翻转矩阵

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

题目要求

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

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

实现 Solution 类

  • Solution(int m, int n) 使用二元矩阵的大小 m 和 n 初始化该对象
  • 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] 的概率应当相同

题解

一、暴力遍历+deepcopy

import copy
class Solution1():
    def __init__(self, m, n):
        self.matrix = []
        for i in range(0, m):
            self.matrix.append([])
            for j in range(0, n):
                self.matrix[i].append(0)
        self.ba = copy.deepcopy(self.matrix)
    def flip(self):
        m = len(self.matrix)
        n = len(self.matrix[0])
        a = random.randrange(0, m)
        b = random.randrange(0, n)
        while(self.matrix[a][b] != 0):
            a = random.randrange(0, m)
            b = random.randrange(0, n)
        self.matrix[a][b] = 1
        return [a, b]
    def reset(self):
        self.matrix = self.ba
        return self.ba

大部分人都能想到的方法,但是会超时,本题没必要新建一个题目所要求的二维数组,只需要将0和1对应的下标记录下来,再对下标进行相应的处理即可。以下给出另外两种解法。

二、set集合

class Solution:
    def __init__(self, n_rows: int, n_cols: int):
        self.s = set()
        self.n = n_rows
        self.m = n_cols
    def flip(self) -> List[int]:
        while True:
            x = (random.randint(0, self.n - 1), random.randint(0, self.m - 1))
            if x not in self.s:
                self.s.add(x)
                return [x[0], x[1]]
    def reset(self) -> None:
        self.s.clear()

三、哈希映射

class Solution:
    def __init__(self, m: int, n: int):
        self.m = m
        self.n = n
        self.total = m * n
        self.map = {}
    def flip(self) -> List[int]:
        x = random.randint(0, self.total - 1)
        self.total -= 1
        # 查找位置 x 对应的映射
        idx = self.map.get(x, x)
        # 将位置 x 对应的映射设置为位置 total 对应的映射
        self.map[x] = self.map.get(self.total, self.total)
        return [idx // self.n, idx % self.n]
    def reset(self) -> None:
        self.total = self.m * self.n
        return self.map.clear()
目录
相关文章
|
2月前
|
算法
力扣240 搜索二维矩阵II
力扣240 搜索二维矩阵II
|
3月前
力扣226:翻转二叉树
力扣226:翻转二叉树
15 0
|
4月前
|
算法 测试技术 C#
【二分查找】LeetCode1970:你能穿过矩阵的最后一天
【二分查找】LeetCode1970:你能穿过矩阵的最后一天
|
4月前
|
Go
golang力扣leetcode 240.搜索二维矩阵II
golang力扣leetcode 240.搜索二维矩阵II
19 0
|
4月前
leetcode-329:矩阵中的最长递增路径
leetcode-329:矩阵中的最长递增路径
23 0
|
2月前
|
机器学习/深度学习 NoSQL Shell
力扣刷题-翻转字符串
力扣刷题-翻转字符串
12 1
|
2月前
|
机器学习/深度学习 人工智能 算法
LeetCode刷题--- 面试题 01.07. 旋转矩阵(原地旋转+翻转替旋转)
LeetCode刷题--- 面试题 01.07. 旋转矩阵(原地旋转+翻转替旋转)
|
4月前
|
算法
【Leetcode 74】搜索二维矩阵 —— 二分查找|矩阵
给你一个满足下述两条属性的`m x n`整数矩阵:每行中的整数从左到右按非严格递增顺序排列。每行的第一个整数大于前一行的最后一个整数
LeetCode | 226. 翻转二叉树
LeetCode | 226. 翻转二叉树
|
4月前
|
算法 测试技术 C#
【map】【动态规划】LeetCode2713:矩阵中严格递增的单元格数
【map】【动态规划】LeetCode2713:矩阵中严格递增的单元格数

热门文章

最新文章