码迷,mamicode.com
首页 > 移动开发 > 详细

LeetCode 528. Random Pick with Weight / 497. Random Point in Non-overlapping Rectangles

时间:2019-09-08 09:49:02      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:leetcode   ble   ppi   怎么办   cts   ping   ber   follow   fas   

528. Random Pick with Weight

根据weight随机选取一个数,用 Prefix Sum+Binary Search 来解决。

https://www.geeksforgeeks.org/random-number-generator-in-arbitrary-probability-distribution-fashion/

class Solution {
public:
    vector<int> prefixSum;
    int total=0;
    
    Solution(vector<int>& w) {
        for (auto x:w){
            total += x;
            prefixSum.push_back(total);
        }
    }
    
    int pickIndex() {
        // random generate from [1,total]
        int r=rand()%total+1;
        
        // find the first >= element
        auto it=lower_bound(prefixSum.begin(),prefixSum.end(),r);
        return it-prefixSum.begin();
    }
};

/**
 * Your Solution object will be instantiated and called as such:
 * Solution* obj = new Solution(w);
 * int param_1 = obj->pickIndex();
 */

 

矩形的内包括点的数量实际就是weight,根据weight先随机选择一个矩形,然后随机生成该矩形内的x和y即可。

class Solution {
public:
    vector<vector<int>> rects;
    vector<int> prefixSum;
    int total=0;
    
    Solution(vector<vector<int>>& rects) {
        this->rects = rects;
        for (auto rect:rects){
            int cur=(rect[2]-rect[0]+1)*(rect[3]-rect[1]+1);
            total += cur;
            prefixSum.push_back(total);
        }
    }
    
    vector<int> pick() {
        // select from [1,total]
        int r=rand()%total+1;
        auto it=lower_bound(prefixSum.begin(),prefixSum.end(),r);
        auto rect=rects[it-prefixSum.begin()];
        
        // randomly pick x from [rect[0],rect[2]], y from [rect[1],rect[3]]
        int x = rect[0] + rand()%(rect[2]-rect[0]+1);
        int y = rect[1] + rand()%(rect[3]-rect[1]+1);

        return {x,y};
    }
};

/**
 * Your Solution object will be instantiated and called as such:
 * Solution* obj = new Solution(rects);
 * vector<int> param_1 = obj->pick();
 */

 

Followup: 如果有overlap的矩形怎么办?

思路:把重复的长方形分成不重复的小块,然后用prefix sum进行二分查找

把一堆重叠长方形变成不重叠的长方形的具体思路可以看这个帖子:

递归解法 https://leetcode.com/problems/rectangle-area-ii/discuss/138028/Clean-Recursive-Solution-Java

迭代解法 https://leetcode.com/problems/rectangle-area-ii/discuss/137995/O(N2)-Maintain-a-List-of-Rectangle-Split-the-Rectangle-in-List-without-overlap

LeetCode 528. Random Pick with Weight / 497. Random Point in Non-overlapping Rectangles

标签:leetcode   ble   ppi   怎么办   cts   ping   ber   follow   fas   

原文地址:https://www.cnblogs.com/hankunyan/p/11484238.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!