Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
记录一种 n^2 解法:
- 掌握最大公约数的求法
- 小数是不准确的,难以作为 key,需要使用字符串代替除法结果
func max(a, b int) int {
if a > b {
return a
}
return b
}
func gcd(a, b int) int {
if b == 0 {
return a
}
return gcd(b, a%b)
}
func maxPoints(points [][]int) int {
if len(points) == 0 {
return 0
}
res := 0
for i := 0; i < len(points); i++ {
// 记录与 points[i] 重合点个数
samePoints := 1
// 记录与 points[i] 相同斜率点的个数(不包括 points[i] 及其重合点)
m := map[string]int{}
// 记录从 points[i] 出发的共线点数的最大值(至少得是 1)
maxCnt := 1
for j := i + 1; j < len(points); j++ {
if points[i][0] == points[j][0] && points[i][1] == points[j][1] {
samePoints++
continue
}
disY := points[j][1] - points[i][1]
disX := points[j][0] - points[i][0]
d := gcd(disY, disX)
disY = disY / d
disX = disX / d
// 关键:除法不准确,这里用最简分数表示斜率
// 数字转字符串不能用 string() 强转,切记
key := fmt.Sprintf("%d:%d", disY, disX)
m[key] += 1
}
if len(m) == 0 {
maxCnt = samePoints
} else {
for _, v := range m {
maxCnt = max(maxCnt, samePoints+v)
}
}
res = max(res, maxCnt)
}
return res
}