【leetcode】519. Random Flip Matrix
题目如下:
You are given the number of rows
n_rowsand number of columnsn_colsof a 2D binary matrix where all values are initially 0. Write a functionflipwhich 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 functionresetwhich 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 <= n_rows, n_cols <= 100000 <= row.id < n_rowsand0 <= col.id < n_colsflipwill not be called when the matrix has no 0 values left.- the total number of calls to
flipandresetwill 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_rowsandn_cols.flipandresethave 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的更多相关文章
- 【LeetCode】519. Random Flip Matrix 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址:https://leetcode.com/problems/random-fl ...
- 519. Random Flip Matrix(Fisher-Yates洗牌算法)
1. 问题 给定一个全零矩阵的行和列,实现flip函数随机把一个0变成1并返回索引,实现rest函数将所有数归零. 2. 思路 拒绝采样 (1)先计算矩阵的元素个数(行乘以列),记作n,那么[0, n ...
- 【LeetCode】566. Reshape the Matrix 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 变长数组 求余法 维护行列 相似题目 参考资料 日期 ...
- 【LeetCode】497. Random Point in Non-overlapping Rectangles 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址: https://leetcode.com/problems/random-p ...
- 【LeetCode】528. Random Pick with Weight 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址:https://leetcode.com/problems/random-pi ...
- 【LeetCode】398. Random Pick Index 解题报告(Python & C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 每次遍历索引 字典保存索引 蓄水池抽样 日期 题目地 ...
- 【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 ...
- 【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 ...
- 【leetcode】566. Reshape the Matrix
原题 In MATLAB, there is a very useful function called 'reshape', which can reshape a matrix into a ne ...
随机推荐
- boost datetime
To create a date, use the class boost::gregorian::date 1. date #include <boost/date_time/gregoria ...
- Security基础(三):OpenSSL及证书服务、邮件TLS/SSL加密通信
一.OpenSSL及证书服务 目标: 本案例要求熟悉OpenSSL工具的基本使用,完成以下任务操作: 使用OpenSSL加密/解密文件 搭建企业自有的CA服务器,为颁发数字证书提供基础环境 方案: 使 ...
- 2018年最新Java面试题及答案整理(持续完善中…)
2018年最新Java面试题及答案整理(持续完善中…) 基础篇 基本功 面向对象特征 封装,继承,多态和抽象 封装封装给对象提供了隐藏内部特性和行为的能力.对象提供一些能被其他对象访问的方法来改变它内 ...
- php使用curl实现get和post请求的方法,数据传输urldecode和json
PHP支持CURL库,利用URL语法规定来传输文件和数据的工具,支持很多协议,包括HTTP.FTP.TELNET等. 优点:是可以通过灵活的选项设置不同的HTTP协议参数,并且支持HTTPS.CURL ...
- 使用 Gradle 快速创建 Java 项目
上一篇介绍了如何安装 Gradle,现在就可以直接通过已经安装好的 Gradle 创建一个普通 Java 项目 Gradle 默认内建了一个 init 插件,可以生成 Java 项目基础结构 $ gr ...
- 搜索的应用--计算最优解:Aizu - ALDS1_4_D Allocation
搜索的应用-计算最优解 题目: You are given nn packages of wiwi kg from a belt conveyor in order (i=0,1,...n−1i=0, ...
- 干货 | Bokeh交互式数据可视化快速入门
Bokeh简介 Bokeh是一款交互式可视化库,在浏览器上进行展示. Bokeh可以通过Python(或其它语言),快速便捷地为大型流数据集提供优雅简洁的高性能交互式图表. 安装 在python中有多 ...
- mysql 【常用sql】
修改过mysql数据库字段内容默认值为当前时间 --添加CreateTime 设置默认时间 CURRENT_TIMESTAMP ALTER TABLE `table_name` ADD COLUMN ...
- Python - zipfile 乱码问题解决
最近使用zipfile进行解包过程中遇到了很不舒服的问题,解包之后文件名是乱码的.下面进行简单总结: 首先,乱码肯定是因为解码方式不一样了,zipfile使用的是utf-8和cp437这两种编码方式, ...
- Groovy学习:第二章 Groovy语言的关键特征
1. 断言Assertion断言:用于判断预期的条件是否为真.例子:def list = [1,2,'x']assert list.size()==32. AST转换期使用的注释AST转换的注释:Gr ...