LeetCode 398 Random Pick Index(蓄水池抽样典型例题)
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.
就是说 给出一个array, 里面有Integers,可以带有重复。现在我们给定一个target,让随机输出array里面值等于target的元素对应的target.当然,如果只有这一个值等于target的元素的话,就直接返回这个index,但是如果有多个的话 就随机返回一个。
要注意,我们保证一定存在这个target.
同时也要注意:array的size可能很大 在解题过程中不要用太多的额外空间。
class Solution {
public Solution(int[] nums) {
}
public int pick(int target) {
}
}
idea:
the initial idea will be just get all the value and it’s index, and we are gonna randomly pick one of them.
so we can choose HashMap<Integer, List< Integer >> map: key: value value: list of indexes.
but array.size() maybe huge and the new hashmap will take too much space.
so can we don’t do any preprocess, and each time we pick it, we iterate num and get all the indexes and randomly get one from them.
but there comes another thing: the size of this array is large, and since we gonna use pick() for many times, so that will be bad in time complexity too.
Actually, after saw the solution, I realized that it is a reservoir sampling
class Solution {
int[] nums;
Random rand;
int N;
public Solution(int[] nums) {
this.nums = nums; //同名的一定要用nums不然会出现null pointer的错误
N = nums.length;
rand = new Random();
}
public int pick(int target) {
int count = 0;
int res = 0;
for (int i = 0; i < N; i++) {
if (nums[i] != target) {
continue;
} else {
count++;
int random = rand.nextInt() % count;
if (random == 0) {
res = i;
}
}
}
return res;
}
}

浙公网安备 33010602011771号