LeetCode 149. 直线上最多的点数

本文探讨了如何解决二维平面上求最多有多少个点在同一直线上的问题,通过计算每两个点之间的斜率并使用哈希表记录斜率出现的次数来找出共线点的最大数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

给定一个二维平面,平面上有 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

对每一个点算出其他各点与它的斜率,用哈希表存储某一斜率被计算出来的次数,也就是在该斜率的直线上有多少个点。

测试数据中的点的情况有3种:
    1. 斜率正常存在
    2. 斜率不存在,横坐标相同
    3. 和之前的点相同 如: [(0,0),(0,0),(0,0)] 最多有3个点在同一条直线上

 

from decimal import Decimal
class Solution:
    def maxPoints(self, points: List[List[int]]) -> int:
        if not len(points):
            return 0;
        res = 0;
        for i in range(len(points)):
            hash_map = dict();
            v = 0
            more = 0
            for j in range(len(points)):
                if j != i:
                    if points[i][0] != points[j][0]:
                        hash_map[Decimal((points[i][1] - points[j][1])) / Decimal((points[i][0] - points[j][0]))] = hash_map.get(Decimal((points[i][1] - points[j][1])) / Decimal((points[i][0] - points[j][0])),0) + 1 
                    elif points[i][0] == points[j][0] and points[i][1] != points[j][1]:
                        v += 1
                    elif points[i][0] == points[j][0] and points[i][1] == points[j][1]:
                        more += 1
            for x in hash_map:
                res = max(res,hash_map[x] + 1 + more)
            res = max(res,v + 1 + more)
        return res;

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值