519. 随机翻转矩阵

519. 随机翻转矩阵


import random
class Solution:

    def __init__(self, m: int, n: int):
        self.m = m
        self.n = n 
        self.size = m*n 
        self.deletedToExist = dict()


    def flip(self) -> List[int]:
        rand = random.randint(0, self.size-1)
        res = rand
        # 这个随机数 可能已经被删掉了
        if res in self.deletedToExist:
            res = self.deletedToExist.get(res)
        
        # 把rand换到数据尾部
        # 数据尾部元素也可能已经被删除
        last = self.size-1
        if last in self.deletedToExist:
            last = self.deletedToExist.get(last)
        
        self.deletedToExist[rand] = last

        self.size -= 1

        return [res//self.n, res%self.n]


    def reset(self) -> None:
        self.size = self.m * self.n 
        self.deletedToExist.clear()



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


你可能感兴趣的:(LeetCode,数据结构与算法,矩阵)