leetcode刷题笔记一百四十九题 直线上最多的点数
源地址:149. 直线上最多的点数
问题描述:
给定一个二维平面,平面上有 n 个点,求最多有多少个点在同一条直线上。
示例 1:
输入: [[1,1],[2,2],[3,3]]
输出: 3
解释:
^
|
| o
| o
| o
+------------->
0 1 2 3 4
示例 2:输入: [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]
输出: 4
解释:
^
|
| o
| o o
| o
| o o
+------------------->
0 1 2 3 4 5 6
//题解参考:https://leetcode-cn.com/problems/max-points-on-a-line/solution/xiang-xi-tong-su-de-si-lu-fen-xi-duo-jie-fa-by--35/
//基本思想是基于点斜式,将构成的斜率构建HashMap,若访问的点构成斜率出现在hash表中(需要使用辗转相除法,使得斜率一致),更新结果,认为其在i点构成的直线上。
//需要注意的是,对重复点的处理,直接统计,在结果计算上添加即可
import scala.collection.mutable
object Solution {
def maxPoints(points: Array[Array[Int]]): Int = {
if (points.length < 3) return points.length
var res = 0
def gcd(x: Int, y: Int): Int = {
var a = x
var b = y
while (b != 0){
val temp = a % b
a = b
b = temp
}
return a
}
for (i <- 0 to points.length-1){
var duplicate = 0
var max = 0
val map = mutable.HashMap[String, Int]()
for (j <- i+1 to points.length-1){
var x: Int = points(j)(0) - points(i)(0)
var y: Int = points(j)(1) - points(i)(1)
if (x == 0 && y == 0) duplicate += 1
else{
//scala中需要注意变量尽量不与函数同名
var gcdAns = gcd(x, y)
x = x / gcdAns
y = y / gcdAns
val key = x + "@" + y
map.put(key, map.getOrElse(key, 0)+1)
max = Math.max(max, map(key))
}
}
res = Math.max(res, max + 1 + duplicate)
}
return res
}
}