LeetCode 478. 在圆内随机生成点
题目描述
思路分析
解法一:极坐标采样(推荐)
核心思路:
- 角度均匀采样于 [0, 2π)。
- 半径使用
sqrt(rand),保证面积均匀分布。- 转为直角坐标并平移到圆心。
复杂度分析:
- 时间复杂度:O(1) 每次采样。
- 空间复杂度:O(1)。
class Solution {
private final double radius;
private final double x;
private final double y;
public Solution(double radius, double x_center, double y_center) {
this.radius = radius;
this.x = x_center;
this.y = y_center;
}
public double[] randPoint() {
double angle = Math.random() * 2 * Math.PI;
double r = Math.sqrt(Math.random()) * radius;
return new double[]{x + r * Math.cos(angle), y + r * Math.sin(angle)};
}
}
import (
"math"
"math/rand"
)
type Solution struct {
radius float64
x float64
y float64
}
func Constructor(radius float64, xCenter float64, yCenter float64) Solution {
return Solution{radius: radius, x: xCenter, y: yCenter}
}
func (s *Solution) RandPoint() []float64 {
angle := rand.Float64() * 2 * math.Pi
r := math.Sqrt(rand.Float64()) * s.radius
return []float64{s.x + r*math.Cos(angle), s.y + r*math.Sin(angle)}
}
相似题目
| 题目 | 难度 | 考察点 |
|---|---|---|
| 384. 打乱数组 | 中等 | 随机化 |
| 528. 按权重随机选择 | 中等 | 随机化 |
| 382. 链表随机节点 | 中等 | 随机化 |
| 470. 用 Rand7() 实现 Rand10() | 中等 | 随机化 |
| 497. 非重叠矩形中的随机点 | 中等 | 随机化 |
本博客所有文章除特别声明外,均采用
CC BY-NC-SA 4.0
许可协议,转载请注明出处!