[LeetCode] 1232. Check If It Is a Straight Line

You are given an array coordinatescoordinates[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:

Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]
Output: true

Example 2:

Input: coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]]
Output: false

 

Constraints:

  • 2 <= coordinates.length <= 1000
  • coordinates[i].length == 2
  • -10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4
  • coordinates contains no duplicate point.

缀点成线。

给定一个数组 coordinates ,其中 coordinates[i] = [x, y] , [x, y] 表示横坐标为 x、纵坐标为 y 的点。请你来判断,这些点是否在该坐标系中属于同一条直线上。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/check-if-it-is-a-straight-line
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题意是给一堆坐标,请你判断这些坐标是否在同一条直线上。

思路就是求每两个点之间组成直线的斜率 slope。需要注意的是斜率的求法是 slope = (y2 - y1) / (x2 - x1) 但是如果直接算两点之间的斜率,有可能会导致分母为 0。所以我们不直接通过除法计算斜率,我们去比较每两点之间的斜率是否一样即可。这里需要把计算斜率的公式转换一下,原本斜率的公式是 y1 / x1(这是前两个点的斜率,纵坐标差值除以横坐标差值),那么从第三个点开始,我们计算 y2 / x2(每个点与他前一个点的纵坐标的差值除以横坐标的差值)。之后去判断 y1 / x1 = y2 / x2。把这个方程转换一下,去判断 x2 * y1 = x1 * y2 即可。具体见代码。

时间O(n)

空间O(1)

Java实现

 1 class Solution {
 2     public boolean checkStraightLine(int[][] coordinates) {
 3         int y1 = coordinates[1][1] - coordinates[0][1];
 4         int x1 = coordinates[1][0] - coordinates[0][0];
 5         // double slope = ydiff / xdiff;
 6         for (int i = 2; i < coordinates.length; i++) {
 7             int y2 = coordinates[i][1] - coordinates[i - 1][1];
 8             int x2 = coordinates[i][0] - coordinates[i - 1][0];
 9             if (x1 * y2 != x2 * y1) {
10                 return false;
11             }
12         }
13         return true;
14     }
15 }

 

相关题目

1232. Check If It Is a Straight Line

2280. Minimum Lines to Represent a Line Chart

LeetCode 题目总结

posted @ 2020-05-09 09:32  CNoodle  阅读(296)  评论(0编辑  收藏  举报