【数学】C078_LC_缀点成线(斜率计算)

一、Problem

在一个 XY 坐标系中有一些点,我们用数组 coordinates 来分别记录它们的坐标,其中 coordinates[i] = [x, y] 表示横坐标为 x、纵坐标为 y 的点。

请你来判断,这些点是否在该坐标系中属于同一条直线上,是则返回 true,否则请返回 false。

在这里插入图片描述

输入:coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]
输出:true

提示:

2 <= coordinates.length <= 1000
coordinates[i].length == 2
-10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4
coordinates 中不含重复的点

二、Solution

方法一:计算斜率

两两枚举即可,并计算斜率即可,斜率公式为
k = y 1 y 0 x 1 x 0 k = \cfrac{y_1-y_0}{x_1-x_0}

注:不要用 abs 将两个数的差值转为正数,因为如果点可能在 x、y 轴上某些负坐标,会 WA。

[[0,0],[0,1],[0,-1]]
class Solution {
    public boolean checkStraightLine(int[][] cs) {
        if (cs.length <= 2)
            return true;
        int xd = cs[1][0]-cs[0][0], yd = cs[1][1]-cs[0][1];
        
        for (int i = 2; i < cs.length; i++) {
            int xx = cs[i][0]-cs[i-1][0], yy = cs[i][1]-cs[i-1][1];
            if (yy*xd != xx*yd)
                return false;
        }
        return true;
    }
}

复杂度分析

  • 时间复杂度: O ( n ) O(n)
  • 空间复杂度: O ( 1 ) O(1)

猜你喜欢

转载自blog.csdn.net/qq_43539599/article/details/106845188