Leetcode 519. Random Flip Matrix

本文介绍了一种高效的算法,用于在二维二进制矩阵中随机选择并翻转一个元素从0到1,同时提供了重置矩阵的方法。通过最小化随机函数调用次数,优化了时间和空间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

You are given the number of rows n_rows and number of columns n_cols of a 2D binary matrix where all values are initially 0. Write a function flip which chooses a 0 value uniformly at random, changes it to 1, and then returns the position [row.id, col.id] of that value. Also, write a function reset which sets all values back to 0. Try to minimize the number of calls to system's Math.random() and optimize the time and space complexity.

Note:

  1. 1 <= n_rows, n_cols <= 10000
  2. 0 <= row.id < n_rows and 0 <= col.id < n_cols
  3. flip will not be called when the matrix has no 0 values left.
  4. the total number of calls to flip and reset will not exceed 1000.

Example 1:

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

Example 2:

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

Explanation of Input Syntax:

The input is two lists: the subroutines called and their arguments. Solution's constructor has two arguments, n_rows and n_colsflip and reset have no arguments. Arguments are always wrapped with a list, even if there aren't any.

--------------------------------------------------------------------------------

思路很巧妙,有点类似于蓄水池抽样,写起来非常容易有bug

import random

class Solution:

    def __init__(self, n_rows: int, n_cols: int):
        self.not_visited = {} #key对应的value还没被随出来过,key之前确实被随即过了
        self.rows = n_rows
        self.cols = n_cols
        self.last = self.rows*self.cols - 1

    def flip(self):
        if (self.last < 0): #bug3
            return None
        x = random.randint(0, self.last)
        y = self.not_visited[x] if x in self.not_visited else x
        self.not_visited[x] = self.last if self.last not in self.not_visited else self.not_visited[self.last] #bug2: self.last之前可能名花有主了
        self.last -= 1
        return [y // self.cols, y % self.cols] #bug1: [y // self.rows, y % self.rows]

    def reset(self):
        self.not_visited.clear()
        self.last = self.rows*self.cols - 1

# Your Solution object will be instantiated and called as such:
obj = Solution(2, 2)
print(obj.flip())
print(obj.flip())
print(obj.flip())
print(obj.flip())
print(obj.flip())
obj.reset()


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值