File tree Expand file tree Collapse file tree 2 files changed +44
-0
lines changed Expand file tree Collapse file tree 2 files changed +44
-0
lines changed Original file line number Diff line number Diff line change 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+ } ;
Original file line number Diff line number Diff line change 536536705|[ Design HashSet] ( ./0705-design-hashset.js ) |Easy|
537537706|[ Design HashMap] ( ./0706-design-hashmap.js ) |Easy|
538538707|[ Design Linked List] ( ./0707-design-linked-list.js ) |Medium|
539+ 710|[ Random Pick with Blacklist] ( ./0710-random-pick-with-blacklist.js ) |Hard|
539540713|[ Subarray Product Less Than K] ( ./0713-subarray-product-less-than-k.js ) |Medium|
540541714|[ Best Time to Buy and Sell Stock with Transaction Fee] ( ./0714-best-time-to-buy-and-sell-stock-with-transaction-fee.js ) |Medium|
541542717|[ 1-bit and 2-bit Characters] ( ./0717-1-bit-and-2-bit-characters.js ) |Easy|
You can’t perform that action at this time.
0 commit comments