[LeetCode] 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.html

Note:
The array size can be very large. Solution that uses too much extra space will not pass the judge. java

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);
 
這道題指明瞭咱們不能用太多的空間,那麼省空間的隨機方法只有 水塘抽樣Reservoir Sampling了,LeetCode以前有過兩道須要用這種方法的題目 Shuffle an ArrayLinked List Random Node。那麼若是瞭解了水塘抽樣,這道題就不算一道難題了,咱們定義兩個變量,計數器cnt和返回結果res,咱們遍歷整個數組,若是數組的值不等於target,直接跳過;若是等於target,計數器加1,而後咱們在[0,cnt)範圍內隨機生成一個數字,若是這個數字是0,咱們將res賦值爲i便可,參見代碼以下:

 

class Solution {
public:
    Solution(vector<int> nums): v(nums) {}
    
    int pick(int target) {
        int cnt = 0, res = -1;
        for (int i = 0; i < v.size(); ++i) {
            if (v[i] != target) continue;
            ++cnt;
            if (rand() % cnt == 0) res = i;
        }
        return res;
    }
private:
    vector<int> v;
};

 

相似題目:dom

Shuffle an Arraypost

Linked List Random Nodeurl

 

參考資料:spa

https://discuss.leetcode.com/topic/58371/c-o-n-solution/2code

https://discuss.leetcode.com/topic/58297/share-c-o-n-time-solution/2htm

https://discuss.leetcode.com/topic/58403/bruce-force-java-with-o-n-time-o-1-spaceblog

 

LeetCode All in One 題目講解彙總(持續更新中...)

相關文章
相關標籤/搜索