【leetcode】Max Points on a Line
2014-11-24 13:10
656 查看
Max Points on a Line
题目描述:
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.解题思路:
1.首先由这么一个O(n^3)的方法,也就是算出每条线的方程(n^2),然后判断有多少点在每条线上(N)。这个方法肯定是可行的,只是复杂度太高2.然后想到一个O(N)的,对每一个点,分别计算这个点和其他所有点构成的斜率,具有相同斜率最多的点所构成的直线,就是具有最多点的直线。
注意的地方:
1.重合的点2.斜率不存在的点
# Definition for a point class Point: def __init__(self, a=0, b=0): self.x = a self.y = b class Solution: # @param points, a list of Points # @return an integer def calcK(self,pa, pb): t = ((pb.y - pa.y) * 1.0) / (pb.x - pa.x) return t def maxPoints(self, points): l = len(points) res = 0 if l <= 2: return l for i in xrange(l): same = 0 k = {} k['inf'] = 0 for j in xrange(l): if points[j].x == points[i].x and points[j].y != points[i].y: k['inf'] += 1 elif points[j].x == points[i].x and points[j].y == points[i].y: same +=1 else: t = self.calcK(points[j],points[i]) if t not in k.keys(): k[t] = 1 else: k[t] += 1 res = max(res, max(k.values())+same) return res def main(): points = [] points.append(Point(0,0)) points.append(Point(1,1)) points.append(Point(1,-1)) #points.append(Point(0,0)) #points.append(Point(1,1)) #points.append(Point(0,0)) s = Solution() print s.maxPoints(points) if __name__ == '__main__': main()
相关文章推荐
- [Leetcode]149. Max Points on a Line @python
- Max Points on a Line -- LeetCode
- max-points-on-a-line(Leetcode)
- LeetCode -- Max Points on a Line
- 【leetcode每日一题】149.Max Points on a line
- Max Points On a Line--leetcode
- leetcode 149. Max Points on a Line
- LeetCode: Max Points on a Line
- leetcode Max Points on a Line(*)
- LeetCode:Max Points on a Line
- [LeetCode] Max Points on a Line
- Max Points on a Line [leetcode]
- LEETCODE: Max Points on a Line
- Leetcode: Max Points on a Line
- Leetcode 149. Max Points on a Line
- LeetCode: Max Points on a Line 解题报告
- 【LeetCode】149. Max Points on a Line - javascript
- [LeetCode][JavaScript]Max Points on a Line
- LeetCode 3 Max Points on a Line
- LeetCode 149. Max Points on a Line(直线上的点)