File tree Expand file tree Collapse file tree 2 files changed +36
-0
lines changed Expand file tree Collapse file tree 2 files changed +36
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * 398. Random Pick Index
3+ * https://leetcode.com/problems/random-pick-index/
4+ * Difficulty: Medium
5+ *
6+ * Given an integer array nums with possible duplicates, randomly output the index of a given
7+ * target number. You can assume that the given target number must exist in the array.
8+ *
9+ * Implement the Solution class:
10+ * - Solution(int[] nums) Initializes the object with the array nums.
11+ * - int pick(int target) Picks a random index i from nums where nums[i] == target. If there
12+ * are multiple valid i's, then each index should have an equal probability of returning.
13+ */
14+
15+ /**
16+ * @param {number[] } nums
17+ */
18+ var Solution = function ( nums ) {
19+ this . map = new Map ( ) ;
20+ for ( let i = 0 ; i < nums . length ; i ++ ) {
21+ if ( ! this . map . has ( nums [ i ] ) ) {
22+ this . map . set ( nums [ i ] , [ ] ) ;
23+ }
24+ this . map . get ( nums [ i ] ) . push ( i ) ;
25+ }
26+ } ;
27+
28+ /**
29+ * @param {number } target
30+ * @return {number }
31+ */
32+ Solution . prototype . pick = function ( target ) {
33+ const result = this . map . get ( target ) ;
34+ return result [ Math . floor ( Math . random ( ) * result . length ) ] ;
35+ } ;
Original file line number Diff line number Diff line change 316316395|[ Longest Substring with At Least K Repeating Characters] ( ./0395-longest-substring-with-at-least-k-repeating-characters.js ) |Medium|
317317396|[ Rotate Function] ( ./0396-rotate-function.js ) |Medium|
318318397|[ Integer Replacement] ( ./0397-integer-replacement.js ) |Medium|
319+ 398|[ Random Pick Index] ( ./0398-random-pick-index.js ) |Medium|
319320399|[ Evaluate Division] ( ./0399-evaluate-division.js ) |Medium|
320321404|[ Sum of Left Leaves] ( ./0404-sum-of-left-leaves.js ) |Easy|
321322405|[ Convert a Number to Hexadecimal] ( ./0405-convert-a-number-to-hexadecimal.js ) |Easy|
You can’t perform that action at this time.
0 commit comments