当前位置:网站首页>非重叠矩形中的随机点(力扣每日一题)
非重叠矩形中的随机点(力扣每日一题)
2022-07-27 05:21:00 【最后一只三脚兽】
非重叠矩形中的随机点


这题主要运用了前缀和和二分查找方法
对于一个矩阵中等概率随机一个点是容易的,难点就在于如何随机矩阵。例如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};
}
}
边栏推荐
- PZK学C语言之数据类型,进制转换,输入输出,运算符,分支语句ifelse
- [concurrent programming series 9] priorityblockingqueue, delayqueue principle analysis of blocking queue
- 【头歌】重生之深度学习篇-Keras(初级)
- 力扣题解 二叉树(6)
- 谈谈为何需要将类的成员函数声明为private
- socket编程一:使用fork()实现最基础的并发模式
- Weidongshan digital photo frame project learning (II) displaying Chinese characters on LCD
- AE 3D粒子系统插件:Trapcode Particular
- malloc和new之间的不同-实战篇
- Leetcode每日一题30. 串联所有单词的子串
猜你喜欢

韦东山 数码相框 项目学习(四)简易的TXT文档显示器(电纸书)

面试常问Future、FutureTask和CompletableFuture

安全帽反光衣检测识别数据集和yolov5模型

18. Convolutional neural network

【11】二进制编码:“手持两把锟斤拷,口中疾呼烫烫烫”?

Xmind 思维导图 2022 v12.0.3中文版更新了哪些内容?

Day 3. Suicidal ideation and behavior in institutions of higher learning: A latent class analysis

Matlab 画图(超详细)
![[MVC Architecture] MVC model](/img/71/e10da490d5f0098c64b33e77d158e7.png)
[MVC Architecture] MVC model

geonode geoserver win10 安装教程(亲测)
随机推荐
Stm32-fsmc extended memory SRAM
socket编程一:使用fork()实现最基础的并发模式
Lightroom classic 2022 v11.4 Chinese version "latest resources"
16. Over fitting and under fitting
导数、偏导数以及梯度
cycleGAN解析
【头歌】重生之我在py入门实训中(9):异常处理
剪枝-量化-转onnx中文系列教程
[first song] rebirth of me in py introductory training (1)
编程学习记录——第9课【操作符】
编程学习记录——第8课【数组与设计五子棋,扫雷游戏】
力扣题解 动态规划(3)
Live Home 3D Pro室内家居设计工具
Weidongshan digital photo frame project learning (IV) simple TXT document display (e-paper book)
安全帽反光衣检测识别数据集和yolov5模型
Can it replace PS's drawing software?
C语言-自定义结构类型
子类调用父类构造函数的时机
李宏毅 2020 深度学习与人类语言处理 DLHLP-Conditional Generation by RNN and Attention-p22
[first song] deep learning of rebirth -keras (elementary)