Leetcode-max-points-on-a-line
2016-07-09 22:34
405 查看
题目描述
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.题目越短,事情越大!
一个二维坐标系中有n个点,求出在同一条直线上的点的个数的最大值。
注意:在同一条线上,不规定横线或竖线,斜线也可以!
这就需要用到斜率了。我们运用暴力搜索,从第一个点开始,记为初始点,依次比较其余所有的点与该点的关系,首先计算相同点的个数,如果不相同的点,计算该点与初始点的斜率,存入HashMap中,key为斜率值,value为2,往后继续 计算斜率,判断HashMap中是否包含该斜率,如果包括,则该斜率对应的value值加1,否则,将该key加入到HashMap中。一层循环结束后,计算HashMap中最大的值,然后加上相同点个数。得出与当前初始点同一条线的个数总和最大值。外层循环结束以后,比较所有的最大值,得出最终的最大值,返回。
* class Point { * int x; * int y; * Point() { x = 0; y = 0; } * Point(int a, int b) { x = a; y = b; } * } */ import java.util.*; public class Solution { public int maxPoints(Point[] points) { int n = points.length; if(n == 0 || points == null) return 0; if(n == 1) return 1; int max = 1; for(int i=0; i<n; i++){ HashMap<Float, Integer> hm = new HashMap<Float, Integer>(); int same = 0; int localmax = 1; for(int j=0; j<n; j++){ if(i == j) continue; if(points[i].x == points[j].x && points[i].y == points[j].y){ same++; continue; //找到相同的,则跳过接下来的步骤,开始下一次循环 } float slope =((float)(points[i].y-points[j].y)) / (points[i].x-points[j].x); if(hm.containsKey(slope)) hm.put(slope, hm.get(slope)+1); else hm.put(slope, 2); } for(Integer value:hm.values()) localmax = Math.max(localmax, value); localmax += same; max = Math.max(max, localmax); } return max; } }
程序参考了:
http://www.cnblogs.com/springfor/p/3896120.html
相关文章推荐
- Handler, AsyncTask用法简单示例
- Python介绍
- LeetCode 238. Product of Array Except Self
- 在JS中Check全角半角
- Java开发中的注解技术
- HTML、CSS中相似的元素、声明以及概念间的差别
- Cocos2d-x Lua基本操作
- “字段将不能置于记录中” 错误一解: dbf文件 多个(32)个长字段(200),创建时即报错。
- python笨办法解决zipfile解压会改变文件最后修改时间的问题
- LeetCode:First Bad Version
- 关于UITableView中Cell的保持/保存 选中状态的简单方法
- 如何把文件夹内文件名批量导出到txt生成清单
- 第二天
- 遍历Map的四种方法
- python视频教程大全集下载
- SQL学习笔记(一)
- 剑指offer面试题6:重建二叉树
- NYOJ三点顺序
- github视频录制播放相关功能-参考
- POJ 1442 Treap模板