|
| 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