【LeetCode】抽樣 sampling(共4題)

第一部分 水塘抽樣 reservoir sampling

水塘抽樣的原理:(應該開一篇新文章)psssshtml

【382】Linked List Random Node (2018年11月15日,新算法)node

給了一個單鏈表,要求等機率的返回單鏈表的一個結點的值。面試

解法:我直接隨便解了,能過,可是確定不是面試官想要的XD。先遍歷一遍鏈表求鏈表長度,而後隨機一個出此次是第 x 個結點,(x = rand() % length),而後再遍歷到這個結點返回值。算法

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     /** @param head The linked list's head.
12         Note that the head is guaranteed to be not null, so it contains at least one node. */
13     Solution(ListNode* head) {
14         ListNode* cur = head;
15         h1 = head;
16         for (; cur; cur = cur->next) {
17             length++;
18         }
19     }
20     
21     /** Returns a random node's value. */
22     int getRandom() {
23         int node = rand() % length;
24         auto cur = h1;
25         for (int i = 0; i < node; ++i) {
26             cur = cur->next;
27         }
28         return cur->val;
29     }
30     int length = 0;
31     ListNode* h1;
32 };
33 
34 /**
35  * Your Solution object will be instantiated and called as such:
36  * Solution obj = new Solution(head);
37  * int param_1 = obj.getRandom();
38  */
View Code

follow-up:What if the linked list is extremely large and its length is unknown to you? Could you solve this efficiently without using extra space?數組

 

【398】Random Pick Index(2018年11月15日,新算法)dom

給了一個數組 nums 和一個目標數字 target,要求完成一個設計的題目,等機率的返回 nums 中值爲 target 的下標。ide

題解:我第一次解仍是依舊按照按照本身節奏,用了一個 unordered_map<int, vector<int>> 記錄數組中值和下標的對應關係。而後在 pick 下標的時候,先把值的下標集合搞出來,而後再隨機這個下標值。函數

 1 class Solution {
 2 public:
 3     Solution(vector<int> nums) {
 4         for (int i = 0; i < nums.size(); ++i) {
 5             mp[nums[i]].push_back(i);
 6         }
 7     }
 8     
 9     int pick(int target) {
10         vector<int> vec = mp[target];
11         int idx = rand() % vec.size();
12         return vec[idx];
13     }
14     unordered_map<int, vector<int>> mp;
15 };
16 
17 /**
18  * Your Solution object will be instantiated and called as such:
19  * Solution obj = new Solution(nums);
20  * int param_1 = obj.pick(target);
21  */
View Code

本題用 reservior sampling 應該怎麼解待補充。this

 

第二部分 拒絕採樣 rejection sampling 

【470】Implement Rand10() Using Rand7()spa

用 rand7() 這個函數生成 rand10() 這個函數的功能。

題解在random專題裏面已經寫了。orz。 公式是 (randX() - 1) * X + (randX() - 1)

random 專題連接:http://www.javashuo.com/article/p-tjdfpvbn-ms.html

 

【478】Generate Random Point in a Circle

相關文章
相關標籤/搜索