Hard-题目53:149. Max Points on a Line
来源:互联网 发布:什么叫网络教育 编辑:程序博客网 时间:2024/06/01 08:40
题目原文:
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
题目大意:
给出2维坐标系内的n个点,求出最多有多少个点共线。
题目分析:
对每个点,使用一个hashmap记录<斜率,点数>,这样就知道与这个点共线的点最多有多少个,然后维护最大值即可。
有几个坑,第一斜率要用double而不是int,第二有重复的点,那么该点的hashmap的所有value都+1,第三有斜率不存在的情况,用一个特殊值记录。
源码:(language:java)
public class Solution { public int maxPoints(Point[] points) { if(points.length <= 0) return 0; if(points.length <= 2) return points.length; int result = 0; for(int i = 0; i < points.length; i++){ HashMap<Double, Integer> hm = new HashMap<Double, Integer>(); int samex = 1; int samep = 0; for(int j = 0; j < points.length; j++){ if(j != i){ if((points[j].x == points[i].x) && (points[j].y == points[i].y)){ samep++; } if(points[j].x == points[i].x){ samex++; continue; } 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, 2); } result = Math.max(result, hm.get(k) + samep); } } result = Math.max(result, samex); } return result; }}
成绩:
46ms,17.98%,27ms,7.06%
cmershen的碎碎念:
粗看还以为是传说中的计算几何,其实也是比较水的一道题,但考虑用hashmap存储斜率的思路还是不太好想到的。
0 0
- Hard-题目53:149. Max Points on a Line
- 149、Max Points on a Line (Hard)
- Leetcode 149. Max Points on a Line (Hard) (cpp)
- LeetCode 149. Max Points on a Line
- 149.Max Points on a Line
- 149. Max Points on a Line
- [leetcode] 149. Max Points on a Line
- leetcode 149. Max Points on a Line
- Leetcode 149. Max Points on a Line
- 149. Max Points on a Line
- LeetCode 149. Max Points on a Line
- leetcode.149. Max Points on a Line
- LeetCode-149.Max Points on a Line
- 149. Max Points on a Line
- leetcode 149. Max Points on a Line
- leetCode 149. Max Points on a Line
- 149. Max Points on a Line
- [LeetCode] 149. Max Points on a Line
- Retrofit缓存网络数据RxCache--RxJava和数据库
- Hard-题目52:68. Text Justification
- Python--python基础知识(2)
- PyQt5:程序图标(2)
- redis的基本数据类型及基本操作(一)
- Hard-题目53:149. Max Points on a Line
- C++转移构造函数与转移赋值函数
- Hard-题目54:126. Word Ladder II
- iOS 开发中关于支付功能的学习心得 ----支付宝
- Hard-题目55:65. Valid Number
- PyQt5:显示提示信息(3)
- Android 在桌面主界面显示对话框
- 统计整数区间[a,b](a、b从键盘输入)中素数的个数,并输出这些素数。
- node to traverse cannot be null!