Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 621bb2b

Browse files
Random Pick Index
1 parent 2246403 commit 621bb2b

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

‎0398_randomPickIndex.js

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* @description Class to hold array of nums and randomply pick index of any value matching target.
3+
* @summary Random Pick Index {@link https://leetcode.com/problems/random-pick-index/}
4+
*/
5+
class Solution {
6+
/**
7+
* @param {number[]} nums Array of number values.
8+
*/
9+
constructor(nums) {
10+
this.nums = nums;
11+
}
12+
13+
/**
14+
* @description Return one of indexes where value === target. Return with equal probability.
15+
* @param {number} target Value to match in the nums array.
16+
* @return {number} Index of randomly picked value matching target.
17+
* Space O(1) - constant number of variables.
18+
* Time O(n) - where n is nums.length.
19+
*/
20+
pick(target) {
21+
let result = 0;
22+
let matchedCount = 0;
23+
24+
for (let index = 0; index < this.nums.length; index++) {
25+
if (this.nums[index] === target) {
26+
matchedCount++;
27+
if (Math.floor(Math.random() * matchedCount) === 0) result = index;
28+
}
29+
}
30+
31+
return result;
32+
}
33+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /