[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

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

思路就是求每两个点之间组成直线的斜率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 }

LeetCode 题目总结

原文地址:https://www.cnblogs.com/cnoodle/p/12855330.html