题目链接

两点间距离

题目描述

给定两个在二维平面下的点 point_Apoint_B,你需要计算并返回这两个点之间的直线距离。

  • 题目以核心代码模式提供,你需要实现 calculateDistance 函数。
  • 输入参数是两个 Point 对象,每个对象包含 xy 两个整型坐标。
  • 返回值要求是一个 double 类型的浮点数。

示例: 输入: point_A = (1,1), point_B = (1,8) 输出: 7.0

解题思路

这是一个基础的几何问题,要求计算两点间的欧几里得距离。解决这个问题的关键就是直接应用数学中的距离公式。

对于二维平面上的两个点 ,它们之间的距离 由以下公式给出:

算法步骤如下

  1. 从输入的 Point 对象中分别获取
  2. 计算 坐标的差值
  3. 计算 坐标的差值
  4. 计算上述差值的平方和:
  5. 使用 hypot 函数计算该和的平方根,并将结果返回。

为了数值计算的稳定性和代码的简洁性,可以直接使用 hypot 函数(C++、Java 和 Python 中均有提供),它专门用于计算 ,并且通常比 sqrt(dx*dx + dy*dy) 更精确,可以避免中间计算发生上溢或下溢。

代码

/**
 * struct Point {
 *  int x;
 *  int y;
 *  Point(int xx, int yy) : x(xx), y(yy) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * @param point_A Point类 A点
     * @param point_B Point类 B点
     * @return double浮点型
     */
    double calculateDistance(Point point_A, Point point_B) {
        double dx = point_A.x - point_B.x;
        double dy = point_A.y - point_B.y;
        return hypot(dx, dy);
    }
};
import java.util.*;

/*
 * public class Point {
 *   int x;
 *   int y;
 *   public Point(int x, int y) {
 *     this.x = x;
 *     this.y = y;
 *   }
 * }
 */
public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * @param point_A Point类 A点
     * @param point_B Point类 B点
     * @return double浮点型
     */
    public double calculateDistance(Point point_A, Point point_B) {
        double dx = point_A.x - point_B.x;
        double dy = point_A.y - point_B.y;
        // Math.hypot is specifically for sqrt(x^2 + y^2) and is often more accurate.
        return Math.hypot(dx, dy);
    }
}
# class Point:
#     def __init__(self, a=0, b=0):
#         self.x = a
#         self.y = b
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 计算A点与B点之间的距离
# @param point_A Point类 A点
# @param point_B Point类 B点
# @return double浮点型
#
import math
class Solution:
    def calculateDistance(self, point_A: Point, point_B: Point) -> float:
        dx = point_A.x - point_B.x
        dy = point_A.y - point_B.y
        # math.hypot is equivalent to sqrt(x**2 + y**2)
        return math.hypot(dx, dy)

算法及复杂度

  • 算法: 欧几里得距离公式
  • 时间复杂度: 。该计算涉及固定数量的算术运算,不随输入坐标值的大小而改变。
  • 空间复杂度: 。除了存储输入和几个临时变量外,没有使用额外的空间。