Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit eec82f3

Browse files
committed
Add solution #710
1 parent 1f739c7 commit eec82f3

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

0710-random-pick-with-blacklist.js

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
* 710. Random Pick with Blacklist
3+
* https://leetcode.com/problems/random-pick-with-blacklist/
4+
* Difficulty: Hard
5+
*
6+
* You are given an integer n and an array of unique integers blacklist. Design an algorithm to
7+
* pick a random integer in the range [0, n - 1] that is not in blacklist. Any integer that is
8+
* in the mentioned range and not in blacklist should be equally likely to be returned.
9+
*
10+
* Optimize your algorithm such that it minimizes the number of calls to the built-in random
11+
* function of your language.
12+
*
13+
* Implement the Solution class:
14+
* - Solution(int n, int[] blacklist) Initializes the object with the integer n and the
15+
* blacklisted integers blacklist.
16+
* - int pick() Returns a random integer in the range [0, n - 1] and not in blacklist.
17+
*/
18+
19+
/**
20+
* @param {number} n
21+
* @param {number[]} blacklist
22+
*/
23+
var Solution = function(n, blacklist) {
24+
this.size = n - blacklist.length;
25+
this.mapping = new Map();
26+
blacklist = new Set(blacklist);
27+
28+
let last = n - 1;
29+
for (const b of blacklist) {
30+
if (b < this.size) {
31+
while (blacklist.has(last)) last--;
32+
this.mapping.set(b, last--);
33+
}
34+
}
35+
};
36+
37+
/**
38+
* @return {number}
39+
*/
40+
Solution.prototype.pick = function() {
41+
const index = Math.floor(Math.random() * this.size);
42+
return this.mapping.get(index) ?? index;
43+
};

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -536,6 +536,7 @@
536536
705|[Design HashSet](./0705-design-hashset.js)|Easy|
537537
706|[Design HashMap](./0706-design-hashmap.js)|Easy|
538538
707|[Design Linked List](./0707-design-linked-list.js)|Medium|
539+
710|[Random Pick with Blacklist](./0710-random-pick-with-blacklist.js)|Hard|
539540
713|[Subarray Product Less Than K](./0713-subarray-product-less-than-k.js)|Medium|
540541
714|[Best Time to Buy and Sell Stock with Transaction Fee](./0714-best-time-to-buy-and-sell-stock-with-transaction-fee.js)|Medium|
541542
717|[1-bit and 2-bit Characters](./0717-1-bit-and-2-bit-characters.js)|Easy|

0 commit comments

Comments
 (0)