美文网首页Leetcode
Leetcode 519. Random Flip Matrix

Leetcode 519. Random Flip Matrix

作者: SnailTyan | 来源:发表于2021-09-29 09:36 被阅读0次

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Random Flip Matrix

2. Solution

解析:Version 1,使用单一数字作为矩阵的坐标索引,利用字典来保存访问过的矩阵索引,如果随机得到的索引在字典中存在,则继续进行随机索引,直至找到一个未访问过的索引,如果所有索引都访问过,则返回空坐标。

  • Version 1
class Solution:

    def __init__(self, m: int, n: int):
        self.m = m
        self.n = n
        self.coordinates = m * n
        self.visited = {}


    def flip(self) -> List[int]:
        if len(self.visited) == self.coordinates:
            return []
        index = random.randrange(self.coordinates)
        while index in self.visited:
            index = random.randrange(self.coordinates)
        self.visited[index] = 1
        return [index // self.n, index % self.n]


    def reset(self) -> None:
        self.visited = {}


# Your Solution object will be instantiated and called as such:
# obj = Solution(m, n)
# param_1 = obj.flip()
# obj.reset()

Reference

  1. https://leetcode.com/problems/random-flip-matrix/

相关文章

网友评论

    本文标题:Leetcode 519. Random Flip Matrix

    本文链接:https://www.haomeiwen.com/subject/wqumiltx.html