题目如下:

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 resethave no arguments. Arguments are always wrapped with a list, even if there aren't any.

解题思路:每一个row最多可以生成col次,我的想法是创建一个row_pool,同时有一个字典保存每个row已经使用的次数。如果已经使用了col次,则把row从对应的row_pool里面删除,这样就可以保证只用一次随机就可以在row_pool里面找到可用的row。col也是一样的原理,用第二个字典记录每个row还能使用的col列表,每使用一个col,就从col列表中删除,保证只用一次随机就可以在col列表里面找到可用的col。

代码如下:

class Solution(object):

    def __init__(self, n_rows, n_cols):
"""
:type n_rows: int
:type n_cols: int
"""
self.rows_pool = range(n_rows)
self.dic_rows_count = {}
self.row_can_use_cols = {}
self.row = n_rows
self.col = n_cols def flip(self):
"""
:rtype: List[int]
"""
import random
import bisect
r = random.randint(0, len(self.rows_pool)-1)
r = self.rows_pool[r]
self.dic_rows_count[r] = self.dic_rows_count.setdefault(r,0) + 1
if self.dic_rows_count[r] == self.col:
del self.rows_pool[bisect.bisect_left(self.rows_pool,r)] if r not in self.row_can_use_cols:
self.row_can_use_cols[r] = range(self.col) c = random.randint(0, len(self.row_can_use_cols[r]) - 1)
c = self.row_can_use_cols[r][c]
del self.row_can_use_cols[r][bisect.bisect_left(self.row_can_use_cols[r], c)]
return [r,c] def reset(self):
"""
:rtype: None
"""
self.rows_pool = range(self.row )
self.dic_rows_count = {}
self.row_can_use_cols = {} # Your Solution object will be instantiated and called as such:
# obj = Solution(n_rows, n_cols)
# param_1 = obj.flip()
# obj.reset()

【leetcode】519. Random Flip Matrix的更多相关文章

  1. 【LeetCode】519. Random Flip Matrix 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址:https://leetcode.com/problems/random-fl ...

  2. 519. Random Flip Matrix(Fisher-Yates洗牌算法)

    1. 问题 给定一个全零矩阵的行和列,实现flip函数随机把一个0变成1并返回索引,实现rest函数将所有数归零. 2. 思路 拒绝采样 (1)先计算矩阵的元素个数(行乘以列),记作n,那么[0, n ...

  3. 【LeetCode】566. Reshape the Matrix 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 变长数组 求余法 维护行列 相似题目 参考资料 日期 ...

  4. 【LeetCode】497. Random Point in Non-overlapping Rectangles 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址: https://leetcode.com/problems/random-p ...

  5. 【LeetCode】528. Random Pick with Weight 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址:https://leetcode.com/problems/random-pi ...

  6. 【LeetCode】398. Random Pick Index 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 每次遍历索引 字典保存索引 蓄水池抽样 日期 题目地 ...

  7. 【leetcode】Search a 2D Matrix

    Search a 2D Matrix Write an efficient algorithm that searches for a value in an m x n matrix. This m ...

  8. 【leetcode】 Search a 2D Matrix (easy)

    Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the follo ...

  9. 【leetcode】566. Reshape the Matrix

    原题 In MATLAB, there is a very useful function called 'reshape', which can reshape a matrix into a ne ...

随机推荐

  1. Python"sorted()"和".sort()"的区别

    sorted(A-LIST)会返回一个新的object,不改变**A-LIST*本身. A-LIST.sort()会直接改变A-List,不产生新的object.

  2. 使用UncaughtExceptionHandler重启线程

    先复习Java中的异常 java.lang.Throwable 顶层父类 |– Error错误:JVM内部的严重问题,如OOM,程序员无法在代码中无法处理. |–Exception异常:普通的问题.通 ...

  3. zoj3229 Shoot the Bullet (有源汇最大流)

    题目大意:文文要给幻想乡的女♂孩子们拍照,一共n天,m个女♂孩子,每天文文至多拍D[i]张照片,每个女♂孩子总共要被文文至少拍G[i]次.在第i天,文文可以拍c[i]个女♂孩子,c[i]个女♂孩子中每 ...

  4. 解决“element表单验证输入的数字检测出来是string”的问题

    form表单: 校验规则: 注意:一.数字类型的验证需要在 v-model 处加上 .number 的修饰符,这是 Vue 自身提供的用于将绑定值转化为 number 类型的修饰符.二.校验中是否添加 ...

  5. AGC033 D~F——[ 值放到角标的DP ][ 思路+DP ][ 思路 ]

    地址:https://atcoder.jp/contests/agc033/ D Complexity dp[ i ][ j ][ k ][ l ] 表示左上角是 ( i , j ) .右下角是 ( ...

  6. 最强DE战斗力

    最强DE战斗力 时间限制: 1 Sec  内存限制: 128 MB提交: 40  解决: 14[提交][状态] 题目描述 春秋战国时期,赵国地大物博,资源非常丰富,人民安居乐业.但许多国家对它虎视眈眈 ...

  7. laravel框架手动删除迁移文件后再次创建报错

    手动删除laravel框架数据表迁移文件后再次创建报错 如下图: 执行创建操作之后会在autoload_static.php及autoload_classmap.php这两个文件中添加迁移文件的目录. ...

  8. Python 进阶_OOP 面向对象编程_类属性和方法

    目录 目录 类属性 调用类属性 查看类属性 特殊的类属性 类方法 真构造器 __new__ 类属性 在理解类属性之前要先搞清楚 实例属性 和 函数属性 之间的区别: 1. 实例属性:指的是实例化类对象 ...

  9. CSS属性去除图片链接时的虚线框

    CSS 之outline (轮廓)是绘制于元素周围的一条线,位于边框边缘的外围,可起到突出元素的作用.outline 属性是一个简写属性,用于设置元素周围的轮廓线.注释:轮廓线不会占据空间,也不一定是 ...

  10. mysql中@ROW的使用

    一.从test02表中查询每个uid最早登录的前2天 表如下图所示: select * from (select uid,day, @ROW := END rn, @uuid:=uid from (s ...