注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号 
x
本帖最后由 csy99 于 2021-8-14 15:49 编辑
算是非常经典的一道题:输入n个点的横纵坐标,求所有点对之中最短距离。基本思路就是分治法。自己实在debug不出来。有一个数据量非常大的case没有通过。请大家帮忙看看,谢谢!这里给出OJ的链接https://www.lintcode.com/problem/966/description。
[i][i][i][/i][/i][/i][i][i][i][i][i]- [/i][/i][/i][/i][/i][/i]
- [i][i][i][i][i][i]public class Solution {
- /**
- * @param x: the list of coordinate x
- * @param y: the list of coordinate y
- * @return: find the closest pair of points and return the distance
- */
- public double getClosestDistance(double[] x, double[] y) {
- int n = x.length;
- Point[] points = new Point[n];
- for (int i = 0; i < n; i++)
- points = new Point(x, y);
- Arrays.sort(points, (a,b)->(Double.compare(a.x, b.x)));
- return split(points, 0, n-1);
- }
- private double bruteForce(Point[] points, int start, int end) {
- double min = Integer.MAX_VALUE;
- for (int i = start; i <= end; i++)
- for (int j = i+1; j <= end; j++)
- min = Math.min(min, Point.distance(points, points[j]));
- return min;
- }
- private double split(Point[] points, int start, int end) {
- int n = end-start+1;
- if (n <= 3) return bruteForce(points, start, end);
- Point midX = points[n/2];
- double dl = split(points, start, start+n/2);
- double dr = split(points, start+n/2+1, end);
- double d = Math.min(dl, dr);
- List<Point> middles = new ArrayList();
- for (int i = start; i <= end; i++) {
- if (Math.abs(points.x - midX.x) <= d)
- middles.add(points);
- }
- return Math.min(d, crossRegionMin(middles, d));
- }
- private double crossRegionMin(List<Point> points, double min) {
- Collections.sort(points, (a,b)->(Double.compare(a.y, b.y)));
- for (int i = 0; i < points.size(); i++) {
- for (int j = i+1; j < points.size(); j++) {
- if (points.get(j).y - points.get(i).y >= min)
- break;
- if (Point.distance(points.get(i), points.get(j)) < min)
- min = Point.distance(points.get(i), points.get(j));
- }
- }
- return min;
- }
- }
- class Point {
- double x, y;
- public Point(double x_, double y_) {
- x = x_;
- y = y_;
- }
- public static double distance(Point a, Point b) {
- return Math.sqrt((a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y));
- }
- } [/i][/i][/i][/i][/i][/i]
- [i][i][i][i][i][i]
复制代码
[/i][/i][/i][/i][/i]
|