Leetcode 519. Random Flip Matrix

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

1. Description

Random Flip Matrix

2. Solution

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

  • Version 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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/
如果有收获,可以请我喝杯咖啡!