生活随笔
收集整理的這篇文章主要介紹了
LeetCode 519. 随机翻转矩阵(哈希)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
1. 題目
題中給出一個 n_rows 行 n_cols 列的二維矩陣,且所有值被初始化為 0。
要求編寫一個 flip 函數(shù),均勻隨機的將矩陣中的 0 變?yōu)?1,并返回該值的位置下標 [row_id,col_id];
同樣編寫一個 reset 函數(shù),將所有的值都重新置為 0。
盡量最少調用隨機函數(shù) Math.random(),并且優(yōu)化時間和空間復雜度。
注意
:
1 <= n_rows
, n_cols
<= 10000
0 <= row
.id
< n_rows 并且
0 <= col
.id
< n_cols
當矩陣中沒有值為
0 時,不可以調用 flip 函數(shù)
調用 flip 和 reset 函數(shù)的次數(shù)加起來不會超過
1000 次示例
1:
輸入
:
["Solution","flip","flip","flip","flip"]
[[2,3],[],[],[],[]]
輸出
: [null
,[0,1],[1,2],[1,0],[1,1]]示例
2:
輸入
:
["Solution","flip","flip","reset","flip"]
[[1,2],[],[],[],[]]
輸出
: [null
,[0,0],[0,1],null
,[0,0]]
輸入語法解釋:
輸入包含兩個列表:被調用的子程序和他們的參數(shù)。
Solution 的構造函數(shù)有兩個參數(shù),分別為 n_rows 和 n_cols。
flip 和 reset 沒有參數(shù),參數(shù)總會以列表形式給出,哪怕該列表為空
來源:力扣(LeetCode) 鏈接:https://leetcode-cn.com/problems/random-flip-matrix
著作權歸領扣網(wǎng)絡所有。商業(yè)轉載請聯(lián)系官方授權,非商業(yè)轉載請注明出處。
2. 解題
類似題目:LeetCode 398. 隨機數(shù)索引(概率)
2.1 超時解
- 矩陣很大的時候,翻得時候效率很低,會碰到翻過的,還要去重新翻
class Solution { vector
<int> grid
;int m
, n
;int x
, y
, pos
;
public:Solution(int n_rows
, int n_cols
) {grid
= vector
<int> (n_rows
*n_cols
, 0);m
= n_rows
;n
= n_cols
;}vector
<int> flip() {do{pos
= rand()%(m
*n
);}while(grid
[pos
] == 1);grid
[pos
] = 1;return {pos
/n
, pos
-pos
/n
*n
};}void reset() {grid
= vector
<int> (m
*n
, 0);}
};
2.2 轉一維,每次縮小范圍
- 記錄總共的元素個數(shù)N,隨機獲取 0 ~ N-1 的 pos
- 如果map中有key = pos,則 pos = map[pos],如果沒有,pos就是pos
- 還需要把當前取的位置的 map的 value 更新為最后一個位置的,下一輪,最后那個位置就跳過了
class Solution {unordered_map
<int,int> map
;int m
, n
, num
;int x
, y
, pos
, prev
;
public:Solution(int n_rows
, int n_cols
) {m
= n_rows
;n
= n_cols
;num
= m
*n
;}vector
<int> flip() {if(num
== 0) return {};pos
= rand()%(num
);num
--;if(map
.count(pos
)){prev
= pos
;pos
= map
[pos
];if(!map
.count(num
))map
[prev
] = num
;elsemap
[prev
] = map
[num
];}else{ if(!map
.count(num
))map
[pos
] = num
;elsemap
[pos
] = map
[num
];}x
= pos
/n
;y
= pos
-x
*n
;return {x
, y
};}void reset() {num
= m
*n
;map
.clear();}
};
36 ms 18.6 MB
總結
以上是生活随笔為你收集整理的LeetCode 519. 随机翻转矩阵(哈希)的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內容還不錯,歡迎將生活随笔推薦給好友。