当前位置:   article > 正文

非重叠矩形中的随机点(力扣每日一题)

非重叠矩形中的随机点

非重叠矩形中的随机点
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
这题主要运用了前缀和二分查找方法
对于一个矩阵中等概率随机一个点是容易的,难点就在于如何随机矩阵。例如11的矩阵和22的矩阵随机的概率是不一样的,同时由于矩阵最大面积为10的18次方,把所有可能的点放入一个数组中随机也不现实。

实质上每个矩阵随机到的概率是由它的面积决定的,因此我们可以把所有矩阵的面积加起来,面积之和记作sum,在[1,sum]中随机取一个数,这个数属于的矩阵就是随机矩阵,要做到这点就可以用前缀和加上二分查找来完成

class Solution {
     int[][] rects;
    int[] sum;
    int n;
    Random random = new Random();
    public Solution(int[][] rects) {
        this.rects = rects;
        n = rects.length;
        sum = new int[n+1];
        //前缀和
        for(int i=1;i<=n;i++){
            sum[i] = sum[i-1] + (rects[i-1][2]-rects[i-1][0] + 1) * (rects[i-1][3]-rects[i-1][1] + 1);
        }
    }
    

    public int[] pick() {
        int val = random.nextInt(sum[n]) + 1;
        int l = -1,r = n+1;
        while(l+1 < r){
            int mid = l+r>>1;
            if(val <= sum[mid]){
                r = mid;
            }
            else l = mid;
        }
        //找到随机的矩阵
        int index = r-1;//index为val所在面积的矩阵
		//在矩阵中随机一点
        int y = random.nextInt(rects[index][3]-rects[index][1] + 1) + rects[index][1];
        int x = random.nextInt(rects[index][2]-rects[index][0] + 1) + rects[index][0];

        return new int[]{x, y};
    }
}





  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号