前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >149. Max Points on a Line - 草稿

149. Max Points on a Line - 草稿

作者头像
用户1733462
发布2018-06-07 15:05:08
2430
发布2018-06-07 15:05:08
举报
文章被收录于专栏:数据处理数据处理

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

这个题目难不是很难,建立一个dict,斜率:该斜率上点的个数,算斜率特别要注意,如果使用Fraction(3,4),则会非常影响性能,使用np.longdouble(1)满足要求,真是坑爹。

代码语言:javascript
复制
from fractions import Fraction
from collections import defaultdict
import numpy as np
d = defaultdict(lambda: 100)
class Solution(object):                
    def isequalpt(self, p1, p2):
        if p1.x == p2.x and p1.y == p2.y:
            return True
        else:
            return False
    def maxPointsatPoint(self, points):
        pt = points[0]
        del points[0]
        i = 0
        maxnum = 0
        same = 1
        dic = defaultdict(lambda: 0)
        while i < len(points):
            p = points[i]
            if self.isequalpt(pt, p):
                same += 1
                # 并且把p删除
                points.remove(p)
                continue
            if pt.x != p.x:
                k = (p.y-pt.y)*np.longdouble(1)/(p.x-pt.x)
                dic[k] += 1
                maxnum = max(maxnum, dic[k])
            else:
                dic['zero'] += 1
                maxnum = max(maxnum, dic['zero'])
            i += 1
        maxnum += same
        return maxnum
     
    def maxPoints(self, points):
        """
        :type points: List[Point]
        :rtype: int
        """
        lens = len(points)  
        print lens
        if lens < 3:
            return lens
        self.dic=None
        self.maxnumAll = 0
        i = 0
        while lens > 2:
            lr = self.maxPointsatPoint(points)
            self.maxnumAll = max(self.maxnumAll, lr)
            lens = len(points)
        
        return self.maxnumAll
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017.09.01 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档