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.

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);

S: Reservoir Sampling O(n)

假设目前有count个数等于 target,有1/count的几率选用该数。那么对于第count + 1个数,有1/(count + 1) 的概率被选,

1 - 1/(count+1) = count/(count+1)的概率落选, 此时第count个数仍然入选的概率为(1/count)*(count/(count+1))=1/(count+1)。

故只要保证每个candidate入选的概率为1/count,count为当前candidate的个数,则他们入选的概率都为1/n,n为candidate的总数。

lass Solution {
public:
    Solution(vector<int> nums) {
        num = nums;
    }

    int pick(int target) {
        int count = 0, result = -1;
        for (int i = 0; i < num.size(); ++i) {
            if (num[i] != target) {
                continue;
            } 
            if (rand() % (count + 1) == 0) { // with 1/count posibility to replace original result
                result = i;                  // count == 0 first appearance will be selected directly
            }
            count++;
        }
        return result;
    }

private:
    vector<int> num;
};

results matching ""

    No results matching ""