題目如下:
這道題的思路爲將2維矩陣降爲一維,從而方便使用random函數獲取位置。由於我們只對值爲0的元素進行翻轉,所以需要避免已經被翻轉過的元素。在代碼中我們使用了一個set(因爲我們只關心存在與否)來對翻轉過的位置進行存儲。
參考代碼如下:
'''
@auther: Jedi.L
@Date: Wed, Feb 20, 2019 11:44
@Email: [email protected]
'''
import random
class Solution:
def __init__(self, n_rows, n_cols):
"""
:type n_rows: int
:type n_cols: int
"""
self.cols = n_cols
self.end = n_rows * n_cols - 1
self.fliped = set()
self.start = 0
def flip(self):
"""
:rtype: List[int]
"""
while True:
position = random.randint(self.start, self.end)
if position not in self.fliped:
self.fliped.add(position)
return divmod(position, self.cols)
def reset(self):
"""
:rtype: void
"""
self.fliped = set()
源碼地址:
https://github.com/jediL/LeetCodeByPython
其它題目:[leetcode題目答案講解彙總(Python版 持續更新)]
(https://www.jianshu.com/p/60b5241ca28e)
ps:如果您有好的建議,歡迎交流 :-D,
也歡迎訪問我的個人博客 苔原帶 (www.tundrazone.com)