📜  到给定目标点的 K 最近点

📅  最后修改于: 2022-05-13 01:56:07.919000             🧑  作者: Mango

到给定目标点的 K 最近点

给定二维平面arr[][]上的点列表、给定点target和整数K 。任务是从给定的点列表中找到离目标最近的K个点。

注意:平面上两点之间的距离是欧几里得距离

例子:

方法:该解决方案基于贪婪方法。这个想法是计算每个给定点到目标的欧几里得距离,并将它们存储在一个数组中。然后根据找到的欧几里得距离对数组进行排序,并打印列表中的前 k 个最近点。

下面是上述方法的实现。

C++
// C++ program to implement of above approach
#include 
using namespace std;
 
// Calculate the Euclidean distance
// between two points
float distance(int x1, int y1, int x2, int y2)
{
    return sqrt(pow((x1 - x2), 2) +
                pow((y1 - y2), 2));
}
 
// Function to calculate K closest points
vector > kClosest(
    vector >& points,
    vector target, int K)
{
 
    vector > pts;
    int n = points.size();
    vector > d;
 
    for (int i = 0; i < n; i++) {
        d.push_back(
            make_pair(distance(points[i][0], points[i][1],
                               target[0], target[1]),
                      i));
    }
 
    sort(d.begin(), d.end());
 
    for (int i = 0; i < K; i++) {
        vector pt;
        pt.push_back(points[d[i].second][0]);
        pt.push_back(points[d[i].second][1]);
        pts.push_back(pt);
    }
 
    return pts;
}
 
// Driver code
int main()
{
    vector > points
        = { { 1, 3 }, { -2, 2 } };
    vector target = { 0, 1 };
    int K = 1;
 
    for (auto pt : kClosest(points, target, K)) {
        cout << pt[0] << " " << pt[1] << endl;
    }
    return 0;
}


Java
// Java program to implement of above approach
import java.util.*;
 
class GFG{
    static class pair
    {
        float first;
        float second;
        public pair(float f, float second) 
        {
            this.first = f;
            this.second = second;
        }   
    }
   
// Calculate the Euclidean distance
// between two points
static float distance(int x1, int y1, int x2, int y2)
{
    return (float) Math.sqrt(Math.pow((x1 - x2), 2) +
                Math.pow((y1 - y2), 2));
}
 
// Function to calculate K closest points
static Vector > kClosest(
    int[][] points,
    int[] target, int K)
{
 
    Vector> pts = new Vector>();
    int n = points.length;
    Vector d = new Vector();
 
    for (int i = 0; i < n; i++) {
        d.add(
            new pair(distance(points[i][0], points[i][1],
                               target[0], target[1]),
                      i));
    }
    Collections.sort(d, (a, b) -> (int)(a.first - b.first));
   
 
    for (int i = 0; i < K; i++) {
        Vector pt = new Vector();
        pt.add(points[(int) d.get(i).second][0]);
        pt.add(points[(int) d.get(i).second][1]);
        pts.add(pt);
    }
 
    return pts;
}
 
// Driver code
public static void main(String[] args)
{
    int[][] points
        = { { 1, 3 }, { -2, 2 } };
    int[] target = { 0, 1 };
    int K = 1;
 
    for (Vector  pt : kClosest(points, target, K)) {
        System.out.print(pt.get(0)+ " " +  pt.get(1) +"\n");
    }
}
}
 
// This code is contributed by 29AjayKumar


Python3
# Python code for the above approach
 
# Calculate the Euclidean distance
# between two points
def distance(x1, y1, x2, y2):
    return ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** ( 1 / 2)
 
# Function to calculate K closest points
def kClosest(points, target, K):
    pts = []
    n = len(points)
    d = []
 
    for i in range(n):
        d.append({
            "first": distance(points[i][0], points[i][1], target[0], target[1]),
            "second": i
        })
     
    d = sorted(d, key=lambda l:l["first"])
 
    for i in range(K):
        pt = []
        pt.append(points[d[i]["second"]][0])
        pt.append(points[d[i]["second"]][1])
        pts.append(pt)
 
    return pts
 
# Driver code
points = [[1, 3], [-2, 2]]
target = [0, 1]
K = 1
 
for pt in kClosest(points, target, K):
    print(f"{pt[0]} {pt[1]}")
 
# This code is contributed by gfgking.


C#
// C# program to implement of above approach
using System;
using System.Collections.Generic;
 
public class GFG {
    public class pair {
        public float first;
        public float second;
 
        public pair(float f, float second) {
            this.first = f;
            this.second = second;
        }
    }
 
    // Calculate the Euclidean distance
    // between two points
    static float distance(int x1, int y1,
                          int x2, int y2)
    {
        return (float) Math.Sqrt(Math.Pow((x1 - x2), 2) +
                                 Math.Pow((y1 - y2), 2));
    }
 
    // Function to calculate K closest points
    static List> kClosest(int[,] points,
                                    int[] target, int K)
    {
 
        List> pts = new List>();
        int n = points.GetLength(0);
        List d = new List();
 
        for (int i = 0; i < n; i++) {
            d.Add(new pair(distance(points[i,0], points[i,1],
                                    target[0], target[1]), i));
        }
 
        for (int i = 0; i < K; i++) {
            List pt = new List();
            pt.Add(points[(int) d[i].second,0]);
            pt.Add(points[(int) d[i].second,1]);
            pts.Add(pt);
        }
 
        return pts;
    }
 
    // Driver code
    public static void Main(String[] args) {
        int[,] points = { { 1, 3 }, { -2, 2 } };
        int[] target = { 0, 1 };
        int K = 1;
 
        foreach (List pt in kClosest(points, target, K))
        {
            Console.Write(pt[0] + " " + pt[1] + "\n");
        }
    }
}
 
// This code is contributed by Rajput-Ji


Javascript



输出
1 3

时间复杂度: O(N * logN)
辅助空间: O(N)