**[Lintcode] Max Points on a Line
来源:互联网 发布:淘宝卖家创业故事 编辑:程序博客网 时间:2024/06/05 03:55
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.\
分析:从每一个点(startPoint)出发,统计到其他点的斜率。在map中存储key=斜率,value=点数量。遇到与startPoint点重合的点,在计算所有点数量时需要加上重合点的总数。另外需要注意int除法转double时精度丢失问题。
/** * 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) { if(points == null) return 0; if(points.length < 3) return points.length; HashMap<Double, Integer> res = new HashMap<Double, Integer>(); int max = 0; for(int i = 0; i < points.length; i++) { res.clear();//important int startPoint = 1;//a for(int j = 0; j < points.length; j++) { if(i == j) continue; if (points[i].x == points[j].x && points[i].y == points[j].y) { startPoint++; continue; } int y = points[i].y - points[j].y; int x = points[i].x - points[j].x; double slope = 0.0; if(x == 0) { slope = Integer.MAX_VALUE; } else { slope = 1.0 * y / x; } res.put(slope, res.containsKey(slope) ? res.get(slope) + 1 : 1); } if (res.keySet().size() == 0) { max = startPoint > max ? startPoint : max; } else { for (double key : res.keySet()) { max = Math.max((startPoint + res.get(key)), max); } } } return max; }}
0 0
- Lintcode - Max points on a line
- lintcode Max Points on a Line
- **[Lintcode] Max Points on a Line
- 【LintCode】Max Points on a Line(笔记)
- Max Points on a Line
- Max Points on a Line
- Max Points on a Line
- Max Points on a Line
- Max Points on a Line
- Max Points on a Line
- Max Points On a Line
- Max Points on a Line
- Max Points on a Line
- Max Points on a Line
- max points on a line
- Max Points on a Line
- Max Points on a Line
- Max Points on a Line
- 在main函数里面执行一个返回false的函数过程中遇到的坑
- centos7 搭建hadoop2.7.3集群的错误调试
- Function(翻译自mozilla developer network)
- 洛谷 P1072 Hankson 的趣味题(暴力版)
- Spring学习笔记 —— AOP(面向切面编程) 之AspectJ
- **[Lintcode] Max Points on a Line
- 10.25
- oracle用户创建、授权和权限设置
- 位运算解决“一个数组中,只有一个数字出现n次,其他数字出现k次”问题
- 【备忘】2016最新独家老罗Android视频教程第二季 下载
- 第二讲 GC(垃圾回收)算法
- Boolean(翻译自mozilla developer network)
- 取消RadioButton前面小圆圈的方法
- java 之前的一些配置及简单运行