LeetCode-613. 直线上的最近距离(简单)

表 point 保存了一些点在 x 轴上的坐标,这些坐标都是整数。

写一个查询语句,找到这些点中最近两个点之间的距离。

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

最近距离显然是 '1' ,是点 '-1' 和 '0' 之间的距离。所以输出应该如下:

| shortest|
|---------|
| 1       |

注意:每个点都与其他点坐标不同,表 table 不会有重复坐标出现。

进阶:如果这些点在 x 轴上从左到右都有一个编号,输出结果时需要输出最近点对的编号呢?

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

审题:和上一题有相似之处,选择最近的两个点,

思考:用大的减去小的就是距离。然后比大小。

解题:

表自连接,构造偏序关系。

-- 自己写
select min(P2.x-P1.x) as `shortest` from point as p1 join point as p2 on(p1.x < p2.x)

-- 官方方法
select min(P2.x-P1.x) as `shortest`
from Point as P1 join Point as P2
    on(P1.x < P2.x)

或者不用偏序

-- 自己写

select min(abs(p2.x-p1.x))as `shortest` from point as p1 join point p2 on(p1.x != p2.x)

-- 官方方法
select min(abs(P2.x-P1.x)) as `shortest`
from Point as P1 join Point as P2
    on(P1.x != P2.x)

知识点:

ABS()函数返回X的绝对值

发布了118 篇原创文章 · 获赞 2 · 访问量 4904

猜你喜欢

转载自blog.csdn.net/Hello_JavaScript/article/details/104310505