Skip to content

Commit 8d80750

Browse files
committed
Add solution #398
1 parent e97c189 commit 8d80750

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -316,6 +316,7 @@
316316
395|[Longest Substring with At Least K Repeating Characters](./0395-longest-substring-with-at-least-k-repeating-characters.js)|Medium|
317317
396|[Rotate Function](./0396-rotate-function.js)|Medium|
318318
397|[Integer Replacement](./0397-integer-replacement.js)|Medium|
319+
398|[Random Pick Index](./0398-random-pick-index.js)|Medium|
319320
399|[Evaluate Division](./0399-evaluate-division.js)|Medium|
320321
404|[Sum of Left Leaves](./0404-sum-of-left-leaves.js)|Easy|
321322
405|[Convert a Number to Hexadecimal](./0405-convert-a-number-to-hexadecimal.js)|Easy|

solutions/0398-random-pick-index.js

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
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+
};

0 commit comments

Comments
 (0)