LeetCode 1232. 缀点成线

题目描述

1232. 缀点成线

思路分析

解法一:向量叉积判共线(推荐)

核心思路

  • 取前两点定义方向向量 (dx, dy)
  • 对每个点 i,判断 (xi - x0, yi - y0)(dx, dy) 的叉积是否为 0。
  • 若所有叉积为 0,则所有点共线。


复杂度分析

  • 时间复杂度:O(n),其中 n 为点的数量。
  • 空间复杂度:O(1)。
class Solution {
    public boolean checkStraightLine(int[][] coordinates) {
        int x0 = coordinates[0][0];
        int y0 = coordinates[0][1];
        int x1 = coordinates[1][0];
        int y1 = coordinates[1][1];

        int dx = x1 - x0;
        int dy = y1 - y0;

        for (int i = 2; i < coordinates.length; i++) {
            int x = coordinates[i][0] - x0;
            int y = coordinates[i][1] - y0;
            if (x * dy != y * dx) {
                return false;
            }
        }
        return true;
    }
}
func checkStraightLine(coordinates [][]int) bool {
    x0, y0 := coordinates[0][0], coordinates[0][1]
    x1, y1 := coordinates[1][0], coordinates[1][1]
    dx, dy := x1-x0, y1-y0

    for i := 2; i < len(coordinates); i++ {
        x := coordinates[i][0] - x0
        y := coordinates[i][1] - y0
        if x*dy != y*dx {
            return false
        }
    }
    return true
}

相似题目

题目 难度 考察点
149. 直线上最多的点数 困难 斜率、哈希
1232. 缀点成线 简单 叉积
223. 矩形面积 中等 几何
812. 最大三角形面积 简单 叉积
587. 安装栅栏 困难 凸包
本文作者:
本文链接: https://hgnulb.github.io/blog/2021/62774450
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!