【我也想刷穿 LeetCode啊】478. 在圆内随机生成点

90 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第24天,点击查看活动详情

现在前端很多岗位面试需要有一定的算法基础,或者说经常刷算法的会优先考虑。

因此每天刷刷LeetCode非常有必要

在这之前我也刷过一些算法题,也希望以后也坚持刷,跟某掘友一样,我也想刷穿 LeetCode

一、题目描述

给定圆的半径和圆心的位置,实现函数 randPoint ,在圆中产生均匀随机点。

实现 Solution 类:

Solution(double radius, double x_center, double y_center) 用圆的半径 radius 和圆心的位置 (x_center, y_center) 初始化对象 randPoint() 返回圆内的一个随机点。圆周上的一点被认为在圆内。答案作为数组返回 [x, y] 。  

示例 1:

输入: 
["Solution","randPoint","randPoint","randPoint"]
[[1.0, 0.0, 0.0], [], [], []]
输出: [null, [-0.02493, -0.38077], [0.82314, 0.38945], [0.36572, 0.17248]]
解释:
Solution solution = new Solution(1.0, 0.0, 0.0);
solution.randPoint ();//返回[-0.02493,-0.38077]
solution.randPoint ();//返回[0.82314,0.38945]
solution.randPoint ();//返回[0.36572,0.17248]

提示:

0 < radius <= 108
-107 <= x_center, y_center <= 107
randPoint 最多被调用 3 * 104 次

来源:力扣(LeetCode) 链接:leetcode.cn/problems/ge… 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

二、思路分析

考虑直接生成单位圆内的点,然后放大、平移即可;

由于圆内越靠近圆心点越少,越是远离圆心点越多。所以如果单纯的用this.radiusMath.random()去生成点所在圆的半径,会导致每个点的概率不同;需要用 this.radiusMath.sqrt(Math.random()) 去使每个点的概率相同

三、代码实现

class Solution{
    constructor(radius, x_center, y_center){
        this.radius = radius;
        this.x_center = x_center;
        this.y_center = y_center;
    }
    randPoint = function() {
        let d = this.radius*Math.sqrt(Math.random()); // 点所在圆的半径
        let th = Math.random()*2*Math.PI; // 角度
        return [d*Math.cos(th)+this.x_center,d*Math.sin(th)+this.y_center];
    };
};

或者可以利用 圆外接正方形 采用拒绝采样的方法。如果生成的点落在圆内,就算是正常的点,如果落在圆外,正方形内,就重新生成。

class Solution{
    constructor(radius, x_center, y_center){
        this.radius = radius;
        this.x_center = x_center;
        this.y_center = y_center;
    }
    randPoint = function() {
        const x = this.x_center-this.radius,
            y = this.y_center-this.radius;
        while(true){
            let d1 = x + Math.random()*2*this.radius,
                d2 = y + Math.random()*2*this.radius;
            if((d1-this.x_center)**2 + (d2-this.y_center)**2<=this.radius**2){
                return [d1,d2];
            }
        }
    };
}; 

四、总结

以上就是本道题的所有内容了,本系列会持续更,欢迎点赞、关注、收藏,另外如有其他的问题,欢迎下方留言给我,我会第一时间回复你,感谢~