给定一个正整数 K,一个圆心在 (0, 0) 处,以及一些点的坐标。任务是找到圆的最小半径,使得至少 k 个点位于圆内。输出最小半径的平方。
例子:
输入:(1, 1), (-1, -1), (1, -1),
k = 3
输出:2
我们需要一个半径至少为 2 的圆来包含 3 个点。
输入:(1, 1), (0, 1), (1, -1),
k = 2
输出:1
我们需要一个半径至少为 1 的圆来包含 2 个点。以 (0, 0) 为圆心、半径为 1 的圆将包含 (1, 1)和 (0, 1)。
其思路是求出每个点到原点 (0, 0) 的欧氏距离的平方。然后,按升序对这些距离进行排序。距离的第 k个元素就是所需的最小半径。
以下是该方法的实现:
<script>
// Javascript program to find minimum radius
// such that atleast k point lie inside
// the circle
// Return minimum distance required so that
// atleast k point lie inside the circle.
function minRadius(k, x, y, n) {
let dis = Array.from({length: n}, (_, i) => 0);
// Finding distance between of each
// point from origin
for (let i = 0; i < n; i++)
dis[i] = x[i] * x[i] + y[i] * y[i];
// Sorting the distance
dis.sort();
return dis[k - 1];
}
// driver function
let k = 3;
let x = [ 1, -1, 1 ];
let y = [ 1, -1, -1 ];
let n = x.length;
document.write(minRadius(k, x, y, n));
// This code is contributed by code_hunt.
</script>
输出:
2
时间复杂度: O(n + nlogn)
辅助空间: O(n)ve。
方法#2:使用二分查找
这段代码使用二分查找法来找到最小半径,使得至少 k 个点位于圆内或圆周上。它首先找到任意两点之间的最大距离,然后在 [0, max_distance] 范围内进行二分查找,找到最小半径。
算法
1. 初始化 left = 0 且 right = 给定点集中任意两点之间的最大距离。
2. 当 left <= right 时,找到 mid = (left + right) / 2
3. 使用简单的线性搜索检查是否存在 k 个点位于半径为 mid 的圆内或圆周上。
4. 如果有 k 个或更多点位于圆内或圆周上,则设 right = mid - 1。
5. 如果少于 k 个点位于圆内或圆周上,则设 left = mid + 1。
6. 二分搜索之后,left 的值将是包含 k 个点所需的最小半径。
示例代码:
// JavaScript implementation of Minimum Radius problem
function dist(p1, p2) {
// Calculate Euclidean distance between two points
return Math.sqrt(Math.pow(p1[0] - p2[0], 2) + Math.pow(p1[1] - p2[1], 2));
}
function count_points_in_circle(points, center, radius) {
// Count the number of points inside or on the
// circumference of the circle
let count = 0;
for (let point of points) {
if (dist(point, center) <= radius) {
count++;
}
}
return count;
}
function MinimumRadius(points, k) {
let left = 0.0;
let right = 0.0;
// Find the maximum distance between any two points
for (let i = 0; i < points.length; i++) {
for (let j = i + 1; j < points.length; j++) {
let d = dist(points[i], points[j]);
if (d > right) {
right = d;
}
}
}
while (left <= right) {
let mid = (left + right) / 2.0;
let found = false;
// Check if there exist k points inside or on the
// circumference of a circle with radius mid
for (let i = 0; i < points.length; i++) {
if (count_points_in_circle(points, points[i], mid) >= k) {
found = true;
break;
}
}
if (found) {
right = mid - 1.0;
} else {
left = mid + 1.0;
}
}
return Math.floor(left);
}
// Example usage
const points = [
[1, 1],
[-1, -1],
[1, -1]
];
const k = 3;
console.log(MinimumRadius(points, k));
输出:
2
时间复杂度: O(n^2 * log(r)),其中 n 是点的数量,r 是任意两点之间的最大距离。
空间复杂度: O(1),因为它只使用恒定量的额外空间,与输入的大小无关。
如果您喜欢此文章,请收藏、点赞、评论,谢谢,祝您快乐每一天。