519. leetcode题目讲解(Python):随机翻转矩阵(Random Flip Matrix )

题目如下:


这道题的思路为将2维矩阵降为一维,从而方便使用random函数获取位置。由于我们只对值为0的元素进行翻转,所以需要避免已经被翻转过的元素。在代码中我们使用了一个set(因为我们只关心存在与否)来对翻转过的位置进行存储。

参考代码如下:

'''
@auther: Jedi.L
@Date: Wed, Feb 20, 2019 11:44
@Email: [email protected]
'''

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

源码地址:
https://github.com/jediL/LeetCodeByPython

其它题目:[leetcode题目答案讲解汇总(Python版 持续更新)]
(https://www.jianshu.com/p/60b5241ca28e)

ps:如果您有好的建议,欢迎交流 :-D,
也欢迎访问我的个人博客 苔原带 (www.tundrazone.com)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章