Skip to content

Commit a2b0455

Browse files
committed
Add solution #519
1 parent 2e427ed commit a2b0455

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -415,6 +415,7 @@
415415
516|[Longest Palindromic Subsequence](./0516-longest-palindromic-subsequence.js)|Medium|
416416
517|[Super Washing Machines](./0517-super-washing-machines.js)|Hard|
417417
518|[Coin Change II](./0518-coin-change-ii.js)|Medium|
418+
519|[Random Flip Matrix](./0519-random-flip-matrix.js)|Medium|
418419
520|[Detect Capital](./0520-detect-capital.js)|Easy|
419420
521|[Longest Uncommon Subsequence I](./0521-longest-uncommon-subsequence-i.js)|Easy|
420421
530|[Minimum Absolute Difference in BST](./0530-minimum-absolute-difference-in-bst.js)|Easy|

solutions/0519-random-flip-matrix.js

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/**
2+
* 519. Random Flip Matrix
3+
* https://leetcode.com/problems/random-flip-matrix/
4+
* Difficulty: Medium
5+
*
6+
* There is an m x n binary grid matrix with all the values set 0 initially. Design an algorithm
7+
* to randomly pick an index (i, j) where matrix[i][j] == 0 and flips it to 1. All the indices
8+
* (i, j) where matrix[i][j] == 0 should be equally likely to be returned.
9+
*
10+
* Optimize your algorithm to minimize the number of calls made to the built-in random function
11+
* of your language and optimize the time and space complexity.
12+
*
13+
* Implement the Solution class:
14+
* - Solution(int m, int n) Initializes the object with the size of the binary matrix m and n.
15+
* - int[] flip() Returns a random index [i, j] of the matrix where matrix[i][j] == 0 and flips
16+
* it to 1.
17+
* - void reset() Resets all the values of the matrix to be 0.
18+
*/
19+
20+
/**
21+
* @param {number} m
22+
* @param {number} n
23+
*/
24+
var Solution = function(m, n) {
25+
this.m = m;
26+
this.n = n;
27+
this.total = m * n;
28+
this.flipped = new Map();
29+
};
30+
31+
/**
32+
* @return {number[]}
33+
*/
34+
Solution.prototype.flip = function() {
35+
const index = Math.floor(Math.random() * this.total--);
36+
const result = this.flipped.get(index) ?? index;
37+
this.flipped.set(index, this.flipped.get(this.total) ?? this.total);
38+
return [Math.floor(result / this.n), result % this.n];
39+
};
40+
41+
/**
42+
* @return {void}
43+
*/
44+
Solution.prototype.reset = function() {
45+
this.total = this.m * this.n;
46+
this.flipped.clear();
47+
};

0 commit comments

Comments
 (0)