LeetCode:Max Points on a Line

来源:互联网 发布:excel 2016 数据有效性 编辑:程序博客网 时间:2024/06/18 13:28

Q:

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

思路:n个点,最多形成 (n-1)! 条线段,利用2个点p[i],p[j](j=i+1)可以得到它们所有的所属直线的斜率.以该斜率为key, Set<Integer>为value,set中存放的是构成该线的的两个点的index.由于是set,index是不会重复的. 然后用一个max变量存储set的size的最大值. 

心血来潮,来一份python版的AC代码:

class Solution(object):    def maxPoints(self, points):        """        :type points: List[Point]        :rtype: int        """        l = len(points)        if l == 1:            return l                    line = {}        max = 0        for i in range(l):# 0 -3            for j in range(i + 1, l):# i+1 - 3                if (points[i].x - points[j].x) == 0:                    a = 1                    b = points[i].x                else:                    a = 1.0 * (points[i].y - points[j].y) / (points[i].x - points[j].x)                    b = 1.0 * points[i].y - a * points[i].x                                    key = str(a) + "-" + str(b)                if line.has_key(key):                    line[key].add(i)                    line[key].add(j)                else:                    line[key] = set()                    line[key].add(i)                    line[key].add(j)                                    if max < len(line[key]):                    max = len(line[key])                            return max


0 0
原创粉丝点击