LeetCode Max Points on a Line
来源:互联网 发布:通达信的行情软件 编辑:程序博客网 时间:2024/06/12 23:58
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
题意:平面上给出n个点,求在同一条直线上的最多点。
思路:主要是用斜率。但是注意,水平和竖直方面上的。水平方向的斜率为0,但是浮点计算时,会出现0.0 和-0.0的问题,所以在计算水平方向时,判断y是否相等。
代码如下:
class Point { int x; int y; Point() { x = 0; y = 0; } Point(int a, int b) { x = a; y = b; }}class Solution{ public int maxPoints(Point[] points) { int result = 0; Map<Double, Integer> hm = new HashMap<Double, Integer>(); for (int i = 0; i < points.length; i++) { int samepoint = 1; int samex = 0; int samey = 0; for (int j = i + 1; j < points.length; j++) { if (points[i].x == points[j].x && points[i].y == points[j].y) { samepoint++; } else if (points[i].x == points[j].x) { samex++; } else if (points[j].y == points[i].y) { samey++; } else { double k = (double)(points[j].y - points[i].y) / (double)(points[j].x - points[i].x); if (hm.containsKey(k)) { hm.put(k, hm.get(k) + 1); } else { hm.put(k, 1); } } } result = Integer.max(result, samepoint + samex); result = Integer.max(result, samepoint + samey); for (Double d : hm.keySet()) { result = Integer.max(result, samepoint + hm.get(d)); } hm.clear(); } return result; }}
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
- 打开Android Studio的时候报error: cannot connect to daemon错误
- 从源码带看Volley的缓存机制
- 立委科普:语言学算法是 deep NLP 绕不过去的坎儿
- Linux操作系统文件系统基础知识详解
- #define+do{} while(0)+peeror的思考
- LeetCode Max Points on a Line
- Centos7配置更新国内yum源
- Node.js + Mongodb 建站学习历程1
- android图片处理的工具代码
- WebView和JavaScrip交互基础
- LayoutInflater的inflate函数用法详解
- cc1: out of memory allocating 3355443200 bytes after a total of 610304 bytes
- 基于c++实现的几种排序算法
- 第3章 数据类型和运行符