1. 程式人生 > >【leetcode】519. Random Flip Matrix

【leetcode】519. Random Flip Matrix

ret dia 同時 position when tor fun 思路 sta

題目如下:

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_cols. flip 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