Shortest Distance Problem
Description
LeetCode Problem 613.
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.
MySQL Solution
1
2
3
select min(abs(p2.x-p1.x)) as shortest
from point p1, point p2
where p1.x != p2.x
LeetCode Database - Easy
LeetCode 175
LeetCode 176
LeetCode 181
LeetCode 182
LeetCode 183
LeetCode 196
LeetCode 197
LeetCode 511
LeetCode 512
LeetCode 577
LeetCode 584
LeetCode 586
LeetCode 595
LeetCode 596
LeetCode 597
LeetCode 603
LeetCode 607
LeetCode 610
LeetCode 613
LeetCode 619
LeetCode 620
LeetCode 627
More LeetCode Database
MySQL Tutorials