LintCode:最多有多少个点在一条直线上
2015-11-24 23:10
309 查看
给出二维平面上的n个点,求最多有多少点在同一条直线上。
您在真实的面试中是否遇到过这个题?
Yes
样例
给出4个点:
一条直线上的点最多有3个。
标签 Expand
解题思路:
O(n^2)的时间复杂度,利用2点求斜率,map保存斜率。
需要注意的是2点元素相等和斜率不存在的情况
您在真实的面试中是否遇到过这个题?
Yes
样例
给出4个点:
(1, 2),
(3, 6),
(0, 0),
(1, 3)。
一条直线上的点最多有3个。
标签 Expand
解题思路:
O(n^2)的时间复杂度,利用2点求斜率,map保存斜率。
需要注意的是2点元素相等和斜率不存在的情况
/** * Definition for a point. * class Point { * int x; * int y; * Point() { x = 0; y = 0; } * Point(int a, int b) { x = a; y = b; } * } */ public class Solution { /** * @param points an array of point * @return an integer */ public int maxPoints(Point[] points) { // Write your code here if (points == null || points.length == 0) return 0; HashMap<Double, Integer> map = new HashMap<>(); int res = 1; for (int i = 0; i < points.length; i++) { map.clear(); int dup = 0; map.put((double)Integer.MIN_VALUE, 1); for (int j = i+1; j < points.length; j++) { if (points[j].x == points[i].x&&points[j].y == points[i].y) { dup++;continue; } double k; if (points[j].x - points[i].x == 0) { k = Integer.MAX_VALUE; } else { k = 0.0 + (double)(points[j].y - points[i].y) / (double)(points[j].x - points[i].x); } if (map.containsKey(k)) { map.put(k, map.get(k) + 1); } else { map.put(k, 2); } } for (int item : map.values()) { if (item+dup > res) { res = item+dup; } } } return res; } }
相关文章推荐
- 不汇报是职场发展的绊脚石
- HTML5学习笔记
- Android学习之在Eclipse看源代码的技巧
- 本地私有CA的创建及证书的签署
- cppconvnet is on line in gitHub
- e
- NFS技术实现图片共享存储
- CSS3里的display
- DOS/WINDOW/LINUX都用什么编写各种语言工具又是用什么开
- A First Look at Rust Language
- 九度 题目1055:数组逆置
- Elasticsearch [2.0] ☞ Java Client API ☞ Query DSL
- 抽象工厂模式
- HDU 1024 Max Sum Plus Plus 简单DP
- matlab 破解教程密钥
- 从头认识java-10.3 自定义异常类型
- hdoj 1059 Dividing
- Android性能优化之常见的内存泄漏
- linux学习之路-前言
- IOS 实现不定参数方法