Skip to content

Latest commit

 

History

History

0613.Shortest Distance in a Line

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 

English Version

题目描述

表: Point

+-------------+------+
| Column Name | Type |
+-------------+------+
| x           | int  |
+-------------+------+
在SQL中,x是该表的主键列。
该表的每一行表示X轴上一个点的位置。

 

找到 Point 表中任意两点之间的最短距离。

返回结果格式如下例所示。

 

示例 1:

输入:
Point 表:
+----+
| x  |
+----+
| -1 |
| 0  |
| 2  |
+----+
输出:
+----------+
| shortest |
+----------+
| 1        |
+----------+
解释:点 -1 和 0 之间的最短距离为 |(-1) - 0| = 1。

 

进阶:如果 Point 表按 升序排列,如何优化你的解决方案?

解法

SQL

# Write your MySQL query statement below
SELECT
    min(abs(p1.x - p2.x)) AS shortest
FROM
    Point AS p1
    JOIN Point AS p2 ON p1.x != p2.x;
# Write your MySQL query statement below
SELECT x - lag(x) OVER (ORDER BY x) AS shortest
FROM Point
ORDER BY 1
LIMIT 1, 1;