[LeetCode] Max Points on a Line
来源:互联网 发布:sql语句 修改 编辑:程序博客网 时间:2024/05/18 17:02
题目:
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
分析:
一个点加一个斜率,就可以唯一的确定一条直线。所以我们对每个点,都计算一下该点和其他点连线的斜率,这样对于这个点来说,相同斜率的直线有多少条,就意味着有多少个点在同一条直线上,因为这些直线是相同的。另外,如果计算过点A和点B的直线,当算到点B时,就不用再和A连线了,因为AB这条直线上的点数已经都计算过了。这里,我们用哈希表,以斜率为key,记录有多少重复直线。需要注意的是,Double是有正0和负0的区分的,所以我们要用if(slope * slope == 0) slope = 0;把负0都变成正0。
代码:
import java.util.HashMap;class Point {int x, y;Point(int x, int y) {this.x = x;this.y = y;}}public class MaxPointsOnALine {public int maxPoints(Point[] points) {if(points.length <= 1) return points.length;int max = Integer.MIN_VALUE;for(int i = 0; i < points.length; i++) {//过当前点的直线组成的哈希表,斜率为keyHashMap<Double, Integer> lines = new HashMap<Double, Integer>();int vertical = 0, same = 1, currMax = 0;for(int j = i + 1; j < points.length; j++) {//统计相同的点if(points[i].x == points[j].x && points[i].y == points[j].y) {same++;continue;}//统计斜率为无穷的点,它们都在一条直线上if(points[i].x == points[j].x) {vertical++;continue;}//计算连线的斜率double slope = ((double)points[i].y - (double)points[j].y) / ((double)points[i].x - (double)points[j].x);//修正负0if(slope * slope == 0) slope = 0;lines.put(slope, lines.containsKey(slope) ? lines.get(slope) + 1 : 1);currMax = Math.max(currMax, lines.get(slope));}//经过该点的直线上最多的点数,我们在无穷斜率和正常斜率中选较大的,还要加上相同的点数currMax = Math.max(vertical, currMax) + same;max = Math.max(currMax, max);}return max;}}
阅读全文
0 0
- Max Points on a Line | leetcode
- Max Points on a Line LEETCODE
- Leetcode: 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
- Leetcode: Max Points on a Line
- LeetCode OJ:Max Points on a Line
- Leetcode Max Points on a Line
- Leetcode: Max Points on a Line .
- [Leetcode] Max Points on a Line (Java)
- 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 - Max Points on a Line
- LeetCode(149)Max Points on a Line
- java引用类型和基本类型的比较
- Mac 安装mysql数据库后如何初始化root密码
- PAT (Advanced Level) Practise 1041 Be Unique (20)
- 旋转数组的最小数字
- 算法设计与分析复习(一):习题解答
- [LeetCode] Max Points on a Line
- 详解线上线下收单业务(1)
- 尺取法
- Linux基本操作及数据库查询
- Akka并发编程——第五节:Actor模型(四) 停止Actor
- 4-10固定定位
- linux系统644、755、777权限详解
- Java常识求阶层!的和 ,获取某个数组中的最小值,定义数组,获得成绩之和,平均成绩,最小成绩,最大成绩。等问题大全
- Revit二次开发——revit怎么给桥梁加钢筋