398. 随机数索引
难度:中等
给定一个可能含有重复元素的整数数组,要求随机输出给定的数字的索引。 您可以假设给定的数字一定存在于数组中。
注意:
数组大小可能非常大。 使用太多额外空间的解决方案将不会通过测试。
示例:
int[] nums = new int[] {1,2,3,3,3};
Solution solution = new Solution(nums);
// pick(3) 应该返回索引 2,3 或者 4。每个索引的返回概率应该相等。
solution.pick(3);
// pick(1) 应该返回 0。因为只有nums[0]等于1。
solution.pick(1);
解答:
class Solution {
//蓄水池抽样
//时间复杂度O(N)。空间复杂度O(1)
private int[] nums;
public Solution(int[] nums) {
this.nums = nums;
}
public int pick(int target) {
Random r = new Random();
int n = 0;
int index = 0;
for(int i = 0; i < nums.length; i++){
if(nums[i] == target){
n++;
if(r.nextInt(n) == 0)
index = i;
}
}
return index;
}
}
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(nums);
* int param_1 = obj.pick(target);
*/
参考自:
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/random-pick-index/solution/jian-dan-javadai-ma-shui-tang-chou-yang-h76d0/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。