【leetcode】519. Random Flip Matrix

题目如下:

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

原文地址:https://www.cnblogs.com/seyjs/p/10489160.html

时间: 2024-11-08 11:06:21

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

【Leetcode】Search a 2D Matrix

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: Integers in each row are sorted from left to right. The first integer of each row is greater than the last integer of the previous ro

【Leetcode】Search a 2D Matrix II

题目链接:https://leetcode.com/problems/search-a-2d-matrix-ii/ 题目: Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: Integers in each row are sorted in ascending from left to right. Intege

【Leetcode】Search a 2D Matrix in JAVA

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: Integers in each row are sorted from left to right. The first integer of each row is greater than the last integer of the previous ro

【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 following properties: Integers in each row are sorted from left to right. The first integer of each row is greater than the last integer of the previous ro

【LeetCode】Copy List with Random Pointer

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null. Return a deep copy of the list. 思路:第一遍正常复制链表,同时用哈希表保存链表中原始节点和新节点的对应关系,第二遍遍历链表的时候,再复制随机域. 这是一种典型的空间换时间的做法,n个节点,需要大小为O(n

【LeetCode】Spiral Matrix II

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. For example,Given n = 3, You should return the following matrix: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]此题与Spiral Matrix类似,可以用相同的方法解决,相比之下,此题比前一题简单 publ

【Leetcode】Set Matrix Zeroes

Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place. Could you devise a constant space solution? 思路:因为需要遍历整个矩阵,时间复杂度肯定需要O(m * n),对于空间复杂度而言,第一种是可以使用O(m * n),对每个位置的0的情况进行记录,第二种是使用O(m + n),对每行每列是否存在0进行记录,第三种是O(1)

【leetcode】Clone Graph(python)

类似于二叉树的三种遍历,我们可以基于遍历的模板做很多额外的事情,图的两种遍历,深度和广度模板同样也可以做很多额外的事情,这里举例利用深度优先遍历的模板来进行复制,深度优先中,我们先访问第一个结点,接着访问第一个邻接点,再访问邻节点的邻节点.... class Solution: # @param node, a undirected graph node # @return a undirected graph node def cloneGraph(self, node): if None =

【Leetcode】Rotate Image

You are given an n x n 2D matrix representing an image. Rotate the image by 90 degrees (clockwise). Follow up: Could you do this in-place? 思路:第一种思路是一层一层的进行旋转,比较直观:第二种思路则比较取巧,首先沿着副对角线翻转一次,然后沿着水平中线翻转一次. 代码一: class Solution { public: void rotate(vector<