Max Points on a Line

Given_n_points on a 2D plane, find the maximum number of points that lie on the same straight line.

Example 1:

Input:
 [[1,1],[2,2],[3,3]]

Output:
 3

Explanation:

^
|
|        o
|     o
|  o  
+-------------
>

0  1  2  3  4

Example 2:

分析

定出发点,找斜率相同直线”的方法。然后遍历所有直线,用HashMap计数,x遍历1-n,y从x+1开始到n。

Map<Integer, Map<Integer, Integer>> map 存的是(x,(y, 此斜率个数))

此处x, y是2个点x1-x2, y1-y2,为了防止溢出,用的gcd最大公约数相除。

此题不用斜率存入Map,因为double的斜率也还是会不准确,用最大公约数把x,y处理了,好让它们不会越界。

注意2次max,第二次才加上共点。

答案

Last updated

Was this helpful?