码迷,mamicode.com
首页 > 数据库 > 详细

[LeetCode] 613. Shortest Distance in a Line_Easy tag: SQL

时间:2018-08-29 01:11:48      阅读:270      评论:0      收藏:0      [点我收藏+]

标签:col   sel   leetcode   range   tco   --   which   most   and   

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.

 

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

 

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

 

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

 

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

 

Follow-up: What if all these points have an id and are arranged from the left most to the right most of x axis?

Code 

Note: 注意要加上 x1.x != x2.x, 否则总是0

SELECT MIN(ABS(x1.x - x2.x)) AS shortest FROM point as x1 JOIN point as x2 WHERE x1.x != x2.x

 

[LeetCode] 613. Shortest Distance in a Line_Easy tag: SQL

标签:col   sel   leetcode   range   tco   --   which   most   and   

原文地址:https://www.cnblogs.com/Johnsonxiong/p/9551752.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!