【LeetCode】抽样 sampling(共4题)

第一部分 水塘抽样 reservoir sampling

水塘抽样的原理:(应该开一篇新文章)pssss

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

给了一个单链表,要求等概率的返回单链表的一个结点的值。

解法:我直接随便解了,能过,但是肯定不是面试官想要的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日,新算法)

给了一个数组 nums 和一个目标数字 target,要求完成一个设计的题目,等概率的返回 nums 中值为 target 的下标。

题解:我第一次解还是依旧按照按照自己节奏,用了一个 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 应该怎么解待补充。

 

第二部分 拒绝采样 rejection sampling 

【470】Implement Rand10() Using Rand7()

用 rand7() 这个函数生成 rand10() 这个函数的功能。

题解在random专题里面已经写了。orz。 公式是 (randX() - 1) * X + (randX() - 1)

random 专题链接:https://www.cnblogs.com/zhangwanying/p/9964660.html

 

【478】Generate Random Point in a Circle

  

posted @ 2018-11-15 19:29  zhangwanying  阅读(558)  评论(0编辑  收藏  举报