Table of Content
题目如下:
这道题的思路为将2维矩阵降为一维,从而方便使用random函数获取位置。由于我们只对值为0的元素进行翻转,所以需要避免已经被翻转过的元素。在代码中我们使用了一个set(因为我们只关心存在与否)来对翻转过的位置进行存储。
参考代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
''' @auther: Jedi.L @Date: Wed, Feb 20, 2019 11:44 @Email: xiangyangan@gmail.com ''' import random class Solution: def __init__(self, n_rows, n_cols): """ :type n_rows: int :type n_cols: int """ self.cols = n_cols self.end = n_rows * n_cols - 1 self.fliped = set() self.start = 0 def flip(self): """ :rtype: List[int] """ while True: position = random.randint(self.start, self.end) if position not in self.fliped: self.fliped.add(position) return divmod(position, self.cols) def reset(self): """ :rtype: void """ self.fliped = set() |
欢迎关注微信公众号“苔原带”

