《leetCode-php》一条直线上的最多点数

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。但是感觉斜率可能导致不准确。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值