LeetCode 149. Max Points on a Line

Problem Statement

(Source) Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.

Solution

Tags: Hash Table, Math.

Note: In Java version of pre-defined code, coordinates of points are pre-defined as integers. So I assume the same applies here in python version.

class Solution(object):
    def maxPoints(self, points):
        """
        :type points: List[Point]
        :rtype: int
        """
        res = 0
        n = len(points)
        for i in xrange(n):
            memo = {}
            duplicate = 0
            for j in xrange(n):
                if (points[j].x, points[j].y) == (points[i].x, points[i].y):
                    duplicate += 1
                elif points[j].x == points[i].x:
                    memo['v'] = memo.get('v', 0) + 1
                elif points[j].y == points[i].y:
                    memo['h'] = memo.get('h', 0) + 1
                else:
                    k = self.slope(points[i], points[j])
                    memo[k] = memo.get(k, 0) + 1
            res = max(res, max(memo.values()) + duplicate if memo else duplicate)
        return res

    def gcd(self, x, y):
        while x % y: x, y = y, x%y
        return y

    def slope(self, p1, p2):
        res = ''
        flag = 1
        x = p1.x - p2.x
        y = p1.y - p2.y
        if x < 0:
            flag *= -1
            x = -x
        if y < 0:
            flag *= -1
            y = -y
        m = self.gcd(x, y)
        if flag == -1:
            res='-'
        res += (str(x/m) + '/' + str(y/m))
        return res

Complexity analysis:

  • Time complexity: O(n2gcd) . For time complexity analysis of gcd, see below reference.

References

(1) Time complexity of Euclid’s Algorithm.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值