Reservior Sampling
Reservior Sampling
1.Idea
2. Implementation
public static List<Integer> reserviorSampling(int[] nums, int k) {
List<Integer> res = new ArrayList<>();
if (nums.length <= k) {
return res;
}
for (int i = 0; i < k; i++) {
res.add(nums[i]);
}
Random rand = new Random();
for (int i = k + 1; i < nums.length; i++) {
int j = rand.nextInt(i);
// If we use j == k here, that means we want an item to be selected with probability 1/i
if (j < k) {
res.set(j, nums[i]);
}
}
return res;
}3. Proof (Mathematical Induction)
4. Time & Space Complexity
Last updated