Leetcode 519. Random Flip Matrix

文章作者:Tyan
博客:noahsnail.com ?|? CSDN ?|? 簡書

1. Description

Random Flip Matrix

2. Solution

解析:Version 1,使用單一數字作為矩陣的坐標索引,利用字典來保存訪問過的矩陣索引,如果隨機得到的索引在字典中存在,則繼續(xù)進行隨機索引,直至找到一個未訪問過的索引,如果所有索引都訪問過,則返回空坐標。

  • 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/
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容