LeetCode: Shortest Distance in a Line

LeetCode: Shortest Distance in a Line

Table point holds the x coordinate of some points on x-axis in a plane, which are all integers.

Write a query to find the shortest distance between two points in these points.

1
2
3
4
5
| x   |
|-----|
| -1 |
| 0 |
| 2 |

The shortest distance is ‘1’ obviously, which is from point ‘-1’ to ‘0’. So the output is as below:

1
2
3
| shortest|
|---------|
| 1 |

Note: Every point is unique, which means there is no duplicates in table point.

1
2
# Write your MySQL query statement below
select min(abs(p1.x-p2.x)) as shortest from point p1 left join point p2 on p1.x != p2.x;