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 Array和
Linked 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; };
類似題目:
參考資料:
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