zoukankan      html  css  js  c++  java
  • Leetcode练习(Python):哈希表类:第149题:直线上最多的点数:给定一个二维平面,平面上有 n 个点,求最多有多少个点在同一条直线上。

    题目:
    直线上最多的点数:给定一个二维平面,平面上有 n 个点,求最多有多少个点在同一条直线上。
    思路:
    使用斜率来判断,但是在计算斜率时要使用精确计算。
    需要考虑不存在斜率,存在斜率和重复点的情况,思路较简单。
    这道题在工商银行FinTech笔试题里做过。
    程序:
    from decimal import Decimal
    class Solution:
        def maxPoints(self, points: List[List[int]]) -> int:
            num_point = len(points)
            if num_point <= 0:
                return 0
            if num_point == 1:
                return 1
            if num_point == 2:
                return 2
            result = 0
            for index1 in range(num_point):
                myHashMap = {'inf': 0}
                twinsPoint = 0
                for index2 in range(num_point):
                    if index1 != index2:
                        if points[index1][0] == points[index2][0] and points[index1][1] != points[index2][1]:
                            myHashMap['inf'] += 1
                        elif points[index1][0] != points[index2][0]:
                            slope = self.mySlope(points[index1], points[index2])
                            if slope in myHashMap:
                                myHashMap[slope] += 1
                            else:
                                myHashMap[slope] = 1
                        else:
                            twinsPoint += 1
                result = max(result, max(myHashMap.values()) + twinsPoint)
            return result + 1
        def mySlope(self, num1, num2):
            return Decimal(num2[1] - num1[1]) / Decimal(num2[0] - num1[0])
  • 相关阅读:
    fork安全的gettid高效实现
    TCP_DEFER_ACCEPT的坑
    TCP Linger的坑
    Blade和其他构建工具有什么不同
    在Blade中结合gperftools检查内存泄露
    GraphViz web版
    用户场景分析
    java-二维数组——with 刘童格
    java-四则运算-五-网页版--with刘童格
    java-四则运算-四
  • 原文地址:https://www.cnblogs.com/zhuozige/p/12809393.html
Copyright © 2011-2022 走看看