2022-1-16 LeetCode 水塘抽样

从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();
 */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值