You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
You are given an array coordinates, coordinates[i] = [x, y], where [x, y] represents the coordinate of a point. Check if these points make a straight line in the XY plane.
You are given an array
coordinates
,coordinates[i] = [x, y]
, where[x, y]
represents the coordinate of a point. Check if these points make a straight line in the XY plane.Example 1:
Example 2:
Constraints:
2 <= coordinates.length <= 1000
coordinates[i].length == 2
-10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4
coordinates
contains no duplicate point.这道题给了一堆二维坐标上的点,问这些点是否在一条直线上。初中的时候应该就学过两点确定一条直线,同时还有如何判断三点共线的问题,本质上就是判断三点中任意两个点组成的直线的斜率是否相同。计算两个点组成的直线的斜率,就是二者的纵坐标之差除以横坐标之差,但用除法的话就存在一个除数为0的问题,所以在比较两条直线的斜率是否相等时,将其变为乘法的形式,能有效的避免除数为0的情况。这道题说了给定的点的个数至少有两个,则可以用前两个点来确定一条直线,然后从第三个点开始遍历,判断每个遍历到的点和前两个点是否共线,就是不停的在验证三点共线问题,若某个点不在直线上,则返回 false,否则最后返回 true 即可,参见代码如下:
Github 同步地址:
#1232
参考资料:
https://leetcode.com/problems/check-if-it-is-a-straight-line/
https://leetcode.com/problems/check-if-it-is-a-straight-line/discuss/408984/JavaPython-3-check-slopes-short-code-w-explanation-and-analysis.
https://leetcode.com/problems/check-if-it-is-a-straight-line/discuss/620096/Java-Python3-CPP-or-Simple-code-with-explanation-or-100-fast-or-O(1)-space
LeetCode All in One 题目讲解汇总(持续更新中...)
喜欢请点赞,疼爱请打赏❤️~.~
微信打赏
|
Venmo 打赏
---|---
The text was updated successfully, but these errors were encountered: