LeetCode 528. Random Pick with Weight / 497. Random Point in Non-overlapping Rectangles
Posted 約束の空
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 528. Random Pick with Weight / 497. Random Point in Non-overlapping Rectangles相关的知识,希望对你有一定的参考价值。
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(); */
497. Random Point in Non-overlapping Rectangles
矩形的内包括点的数量实际就是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
以上是关于LeetCode 528. Random Pick with Weight / 497. Random Point in Non-overlapping Rectangles的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 528. Random Pick with Weight / 497. Random Point in Non-overlapping Rectangles