博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode 519. Random Flip Matrix
阅读量:4186 次
发布时间:2019-05-26

本文共 2159 字,大约阅读时间需要 7 分钟。

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 , 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 randomclass 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()

 

转载地址:http://stfoi.baihongyu.com/

你可能感兴趣的文章
开发微信公众平台的基本功能
查看>>
JSP内置对象的学习
查看>>
用java写文件输入输出流,实现复制粘贴的方法
查看>>
学习JSP的方法步骤(参考)
查看>>
JSP中常见TOMCAT错误代码原因
查看>>
MyEclipse中WEB项目加载mysql驱动方法
查看>>
常见编写JAVA报错总结
查看>>
org.gjt.mm.mysql.Driver和com.mysql.jdbc.Driver的区别
查看>>
UTF-8和GBK有什么区别
查看>>
增加MyEclipse分配内存的方法
查看>>
头痛与早餐
查看>>
[转]在ASP.NET 2.0中操作数据::创建一个数据访问层
查看>>
Linux命令之chmod详解
查看>>
【java小程序实战】小程序注销功能实现
查看>>
leetcode Unique Paths II
查看>>
几个大数据的问题
查看>>
CareerCup Pots of gold game:看谁拿的钱多
查看>>
CarreerCup Sort Height
查看>>
CareerCup Sort an array in a special way
查看>>
CareerCup Find lexicographic minimum in a circular array 循环数组字典序
查看>>