LeetCode MySQL 612. 平面上的最近距离

文章目录

1. 题目

表 point_2d 保存了所有点(多于 2 个点)的坐标 (x,y) ,这些点在平面上两两不重合

写一个查询语句找到两点之间的最近距离,保留 2 位小数。

| x  | y  |
|----|----|
| -1 | -1 |
| 0  | 0  |
| -1 | -2 |

最近距离在点 (-1,-1) 和(-1,2) 之间,距离为 1.00 。所以输出应该为:

| shortest |
|----------|
| 1.00     |

注意:任意点之间的最远距离小于 10000 。

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

2. 解题

# Write your MySQL query statement below
select round(min(sqrt(power(p1.x-p2.x, 2)+power(p1.y-p2.y, 2))), 2) shortest
from point_2d p1, point_2d p2
where p1.x != p2.x or p1.y != p2.y
where (p1.x, p1.y) != (p2.x, p2.y) # 也可以

226 ms

or

限定条件,减少一半的计算

# Write your MySQL query statement below
select round(min(sqrt(power(p1.x-p2.x, 2)+power(p1.y-p2.y, 2))), 2) shortest
from point_2d p1, point_2d p2
where p1.x < p2.x or (p1.x = p2.x and p1.y != p2.y)

185 ms


我的CSDN博客地址 https://michael.blog.csdn.net/

长按或扫码关注我的公众号(Michael阿明),一起加油、一起学习进步!
Michael阿明

猜你喜欢

转载自blog.csdn.net/qq_21201267/article/details/107470508