|
| 1 | +# 随机数索引 |
| 2 | + |
| 3 | +> 难度:中等 |
| 4 | +> |
| 5 | +> https://leetcode-cn.com/problems/random-pick-index/ |
| 6 | +
|
| 7 | +## 题目 |
| 8 | + |
| 9 | +给定一个可能含有重复元素的整数数组,要求随机输出给定的数字的索引。 您可以假设给定的数字一定存在于数组中。 |
| 10 | + |
| 11 | +注意:数组大小可能非常大。 使用太多额外空间的解决方案将不会通过测试。 |
| 12 | + |
| 13 | +### 示例: |
| 14 | + |
| 15 | +``` |
| 16 | +int[] nums = new int[] {1,2,3,3,3}; |
| 17 | +Solution solution = new Solution(nums); |
| 18 | +
|
| 19 | +// pick(3) 应该返回索引 2,3 或者 4。每个索引的返回概率应该相等。 |
| 20 | +solution.pick(3); |
| 21 | +
|
| 22 | +// pick(1) 应该返回 0。因为只有nums[0]等于1。 |
| 23 | +solution.pick(1); |
| 24 | +``` |
| 25 | + |
| 26 | +## 解题 |
| 27 | + |
| 28 | +### 哈希表 |
| 29 | + |
| 30 | +```ts |
| 31 | +/** |
| 32 | + * 哈希表 |
| 33 | + */ |
| 34 | +export class Solution { |
| 35 | + indexMap = new Map<number, number[]>() |
| 36 | + |
| 37 | + /** |
| 38 | + * @desc 时间复杂度 O(N) 空间复杂度 O(N) |
| 39 | + * @param nums |
| 40 | + */ |
| 41 | + constructor(nums: number[]) { |
| 42 | + for (let i = 0; i < nums.length; i++) { |
| 43 | + const num = nums[i] |
| 44 | + if (this.indexMap.has(num)) |
| 45 | + this.indexMap.get(num)!.push(i) |
| 46 | + else |
| 47 | + this.indexMap.set(num, [i]) |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + /** |
| 52 | + * @desc 时间复杂度 O(1) 空间复杂度 O(N) |
| 53 | + * @param nums |
| 54 | + */ |
| 55 | + pick(target: number): number { |
| 56 | + const idxs = this.indexMap.get(target) |
| 57 | + if (!idxs) return -1 |
| 58 | + if (idxs.length === 1) return idxs[0] |
| 59 | + |
| 60 | + return idxs[(Math.random() * idxs.length) >> 0] |
| 61 | + } |
| 62 | +} |
| 63 | +``` |
| 64 | + |
| 65 | +### 水塘抽样 |
| 66 | + |
| 67 | +```ts |
| 68 | +/** |
| 69 | + * 水塘抽样 |
| 70 | + */ |
| 71 | +export class Solution2 { |
| 72 | + /** |
| 73 | + * @desc 时间复杂度 O(1) 空间复杂度 O(1) |
| 74 | + * @param nums |
| 75 | + */ |
| 76 | + constructor(public nums: number[]) {} |
| 77 | + |
| 78 | + /** |
| 79 | + * @desc 时间复杂度 O(N) 空间复杂度 O(1) |
| 80 | + * @param nums |
| 81 | + */ |
| 82 | + pick(target: number): number { |
| 83 | + let ans = 0 |
| 84 | + for (let i = 0, cnt = 0; i < this.nums.length; i++) { |
| 85 | + if (this.nums[i] === target) { |
| 86 | + // 记录target的次数 |
| 87 | + cnt++ |
| 88 | + if ((Math.random() * cnt) >> 0 === 0) ans = i |
| 89 | + } |
| 90 | + } |
| 91 | + |
| 92 | + return ans |
| 93 | + } |
| 94 | +} |
| 95 | +``` |
0 commit comments