Leetcode 149. Max Points on a Line
来源:互联网 发布:两电一邮 知乎 编辑:程序博客网 时间:2024/04/23 15:27
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
思路是:用两个循环去查看所有情况
same 表示两个点完全重合
sameX 表示两个点有相同的x坐标
public int maxPoints(Point[] points) { if (points == null || points.length == 0) return 0; if (points.length <= 2) return points.length; int res = 0, len = points.length; for (int i = 0; i < len; i++) { Point start = points[i]; int same = 1, sameX = 0, max = 0; Map<String, Integer> hm = new HashMap<>(); for (int j = 0; j < len; j++) { if (i == j) continue; Point end = points[j]; if (start.x == end.x && start.y == end.y) same++; else if (start.x == end.x) sameX++; else { String slope = getSlope(start, end); hm.put(slope, hm.getOrDefault(slope, 0) + 1); max = Math.max(max, hm.get(slope)); 计算出相同斜率的最大的个数 } } max = Math.max(max, sameX) + same; 从相同斜率和有相同X坐标的点选出最大的 加上 点完全重合点的个数 res = Math.max(res, max); } return res; } private String getSlope(Point p1, Point p2) { int a = p1.y - p2.y; int b = p1.x - p2.x; if (b == 0) return null; int gcd = a >= b ? gcd(a, b) : gcd(b, a); a /= gcd; b /= gcd; return a + "/" + b; } private int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); }
阅读全文
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
- gradle项目的编译、打包
- Codeforces Round #427 (Div. 2)-C. Star sky(二维前缀和)
- String字符串比较问题详解
- ACM学习知识点记录
- 排序算法---堆排序(Heap Sort)
- Leetcode 149. Max Points on a Line
- java语法糖自动装箱、拆箱与遍历循环
- Hello java
- J2EE for Spring在Idea里无法加载applicationContext.xml问题解决
- python 操作数据库插入语句占位符问题
- (2017多校训练第二场)HDU
- [CTF]python求crc32值的方法
- Codeforces Round #427 (Div. 2)C. Star sky 暴力D. Palindromic characteristics
- Linux安装ftp组件