[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.

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);
 
這道題指明了我們不能用太多的空間,那么省空間的隨機方法只有 水塘抽樣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;
};

 

類似題目:

Shuffle an Array

Linked List Random Node

 

參考資料:

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

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

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

 

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM