Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
在平面上给n个点,求一条直线上最多有几个点。
第一反应是 两两结合,获取直线,判断其他点在不在直线上,复杂度n^3
注意相同的点算是两个点,所以只在第二层循环过滤相同的点,且需要记下有几个相同的点
<?php
class Point {
private $x;
private $y;
public function Point($a = 0,$b = 0) {
$this->x = $a;
$this->y = $b;
}
}
function maxPoints($arrPoint) {
$maxNum = 0;
foreach ($arrPoint as $point1) {
$x1 = $point1->x;
$y1 = $point1->y;
same = 0;
foreach ($arrPoint as $point2) {
$x2 = $point2->x;
$y2 = $point2->y;
if ($x1 == $x2 && $y1 == $y2) {
same ++;
continue;
}
$arrLinePoint = array($point1, $point2);
foreach ($arrPoint as $point3) {
$x3 = $point3->x;
$y3 = $point3->y;
if (($y3 - $y1) * ($x2 - $x1) == ($y2 - $y1) * ($x3 - $x1)) {
$arrLinePoint[] = $point3;
}
}
$num = count($arrLinePoint) + same;
if ($num > $maxNum) {
$maxNum = $num;
}
}
}
return $maxNum;
}
$point1 = new Point(1,2);
$point2 = new Point(2,4);
$point3 = new Point(3,6);
$point4 = new Point(4,8);
$point5 = new Point(3,2);
$arrPoint = array($point2,$point3,$point1,$point5,$point4);
$maxNum = maxPoints($arrPoint);
print_r($maxNum);
还有一种方法,采用斜率哈希,复杂度是n^2。但是感觉斜率可能导致不准确。