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

题目如下:


题目

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

参考代码如下:

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

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

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

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

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容