LeetCode 149. Max Points on a Line
来源:互联网 发布:积分兑换商城源码 php 编辑:程序博客网 时间:2024/04/20 11:17
Problem Statement
(Source) Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
Solution
Tags: Hash Table
, Math
.
Note: In Java version of pre-defined code, coordinates of points are pre-defined as integers. So I assume the same applies here in python version.
class Solution(object): def maxPoints(self, points): """ :type points: List[Point] :rtype: int """ res = 0 n = len(points) for i in xrange(n): memo = {} duplicate = 0 for j in xrange(n): if (points[j].x, points[j].y) == (points[i].x, points[i].y): duplicate += 1 elif points[j].x == points[i].x: memo['v'] = memo.get('v', 0) + 1 elif points[j].y == points[i].y: memo['h'] = memo.get('h', 0) + 1 else: k = self.slope(points[i], points[j]) memo[k] = memo.get(k, 0) + 1 res = max(res, max(memo.values()) + duplicate if memo else duplicate) return res def gcd(self, x, y): while x % y: x, y = y, x%y return y def slope(self, p1, p2): res = '' flag = 1 x = p1.x - p2.x y = p1.y - p2.y if x < 0: flag *= -1 x = -x if y < 0: flag *= -1 y = -y m = self.gcd(x, y) if flag == -1: res='-' res += (str(x/m) + '/' + str(y/m)) return res
Complexity analysis:
- Time complexity:
O(n2⋅gcd) . For time complexity analysis ofgcd
, see below reference.
References
(1) Time complexity of Euclid’s Algorithm.
0 0
- LeetCode 149. Max Points on a Line
- [leetcode] 149. Max Points on a Line
- leetcode 149. Max Points on a Line
- Leetcode 149. Max Points on a Line
- LeetCode 149. Max Points on a Line
- leetcode.149. Max Points on a Line
- LeetCode-149.Max Points on a Line
- leetcode 149. Max Points on a Line
- leetCode 149. Max Points on a Line
- [LeetCode] 149. Max Points on a Line
- LeetCode 149. Max Points on a Line
- [LeetCode]149. Max Points on a Line
- [LeetCode]149. Max Points on a Line
- [LeetCode]149. Max Points on a Line
- Leetcode 149. Max Points on a Line
- [LeetCode] 149. Max Points on a Line
- Leetcode 149. Max Points on a Line
- 【LeetCode】149. Max Points on a Line
- 解决在WIN10下安装microsoft office professional plus 2013 报1920 的错误
- 数据分析服务平台开放API系统设计
- 什么是线程?线程与进程与有什么关系?
- Java集合之Set、SortedSet、NavigableSet
- 分布式服务管理框架-Zookeeper安装与配置(单机、集群)
- LeetCode 149. Max Points on a Line
- SQLNestedException: Cannot create JDBC driver of class '' for connect URL 'null' 解决办法
- 奇偶剪枝-优化(ZOJ 2110 , HDU 1010)
- c语言十个数排序
- Mysql的基本使用命令(2)
- android事件拦截,结论党福音
- JAVA SSH ----Spring对象创建
- 笔记-CCNA与网络安全 第10章 IPv6(1)
- 矩阵的舞蹈