返回题库

直线上最多的点数

Max Points on a Line

专题
Algorithmic Programming / 算法编程
难度
L4
来源
Citadel

题目详情

问题:直线上最多的点数

考察:数组、动态规划

来源:Citadel

链接:https://www.jointaro.com/interviews/questions/max-points-on-a-line/

Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane, return the maximum number of points that lie on the same straight line.

 

Example 1:

Input: points = [[1,1],[2,2],[3,3]]
Output: 3

Example 2:

Input: points = [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]
Output: 4

 

Constraints:

  • 1 <= points.length <= 300
  • points[i].length == 2
  • -104 <= xi, yi <= 104
  • All the points are unique.
解析

思路:枚举每个点作为基点,统计它到其他点的斜率。斜率用 dx、dy 约分后的整数对表示,避免浮点误差;相同斜率数量最大值加上基点就是答案。

复杂度:时间 O(n^2),空间 O(n)。