398. Random Pick Index随机pick函数
Posted 排序和map
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了398. Random Pick Index随机pick函数相关的知识,希望对你有一定的参考价值。
[抄题]:
Given an array of integers with possible duplicates, randomly output the index of a given target number. You can assume that the given target number must exist in the array.
Note:
The array size can be very large. Solution that uses too much extra space will not pass the judge.
Example:
int[] nums = new int[] {1,2,3,3,3}; Solution solution = new Solution(nums); // pick(3) should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning. solution.pick(3); // pick(1) should return 0. Since in the array only nums[0] is equal to 1. solution.pick(1);
[暴力解法]:
时间分析:
空间分析:
[优化后]:
时间分析:
空间分析:
[奇葩输出条件]:
[奇葩corner case]:
[思维问题]:
[一句话思路]:
Random是一个类,要拿来新建对象
[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):
[画图]:
[一刷]:
- 如果nums[i]不是target,就用continue继续
[二刷]:
[三刷]:
[四刷]:
[五刷]:
[五分钟肉眼debug的结果]:
[总结]:
[复杂度]:Time complexity: O() Space complexity: O()
[英文数据结构或算法,为什么不用别的数据结构或算法]:
rnd.nextInt(n)
在方法调用返回介于0(含)和n(不含)伪随机,均匀分布的int值,所以括号内的参数必须 >0
[算法思想:递归/分治/贪心]:
[关键模板化代码]:
[其他解法]:
[Follow Up]:
[LC给出的题目变变变]:
[代码风格] :
以上是关于398. Random Pick Index随机pick函数的主要内容,如果未能解决你的问题,请参考以下文章