Leetcode 519. Random Flip Matrix

文章作者: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/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值