从382的每日一题开始~~发现这个点非常少见
382. 链表随机节点
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* head;
Solution(ListNode* head) {
this->head=head;
}
int getRandom() {
int res=0;
int i=1;
for(auto node=head;node!=nullptr;node=node->next)
{
if(rand()%i==0)
{
res=node->val;
}
i++;
}
return res;
}
};
/**
* Your Solution object will be instantiated and called as such:
* Solution* obj = new Solution(head);
* int param_1 = obj->getRandom();
*/
398. 随机数索引
class Solution {
public:
vector<int> nums;
Solution(vector<int>& nums) {
this->nums=nums;
}
int pick(int target) {
int n=nums.size();
int k=0;//记录这个target出现了多少次了
int res=-1;
vector<int> index;
for(int i=0;i<n;i++){
if(nums[i]==target){
k++;
index.push_back(i);
res=index[rand()%k];
}
}
return res;
}
};
/**
* Your Solution object will be instantiated and called as such:
* Solution* obj = new Solution(nums);
* int param_1 = obj->pick(target);
*/
497. 非重叠矩形中的随机点
class Solution {
public:
vector<vector<int>> rects;
Solution(vector<vector<int>>& rects) {
this->rects=rects;
}
vector<int> pick() {
vector<int> re;
// for(int i=1;i<=rects.size();i++){
// re=rects[rand()%i];
// } 错误写法
//正确写法:根据面积进行概率分配
int total=0;
for(const auto &rect:rects){
int area=(rect[3]-rect[1]+1)*(rect[2]-rect[0]+1);
total+=area;
if(rand()%total<area) re=rect;
}
//------------以上部分用到了水塘抽样知识,而以下部分不需要---------
int x1=re[0],y1=re[1],x2=re[2],y2=re[3];
int px=x1,py=y1;
px=rand()%(x2-x1+1)+x1;
py=rand()%(y2-y1+1)+y1;
return vector<int>{px,py};
}
};
/**
* Your Solution object will be instantiated and called as such:
* Solution* obj = new Solution(rects);
* vector<int> param_1 = obj->pick();
*/