LeetCode: Max Points on a Line [149]
来源:互联网 发布:天猫美工 编辑:程序博客网 时间:2024/05/19 04:54
【题目】
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.【题意】
给定一堆点,要求找出一条线上的最大点数【思路】
没什么好的方法,从每个点P出发,遍历所有的情况从每个点P出发,斜率相同的点即为统一之前上的点
注意两种特殊情况:
1. 两个点重合(即为同一个点)
2. 两个点的很坐标相同,即两天构成的之前垂直于X轴
【代码】
/** * Definition for a point. * struct Point { * int x; * int y; * Point() : x(0), y(0) {} * Point(int a, int b) : x(a), y(b) {} * }; */class Solution {public: int maxPoints(vector<Point> &points) { int max=0; double INFTY = INT_MAX * 1.0; for(int i=0; i<points.size(); i++){ map<double, int> pointNum; //key是直线的斜率,value是这条直线上的点数 int samepoints = 1; //统计和当前点重合点的个数(包括它自己,所以初始化为1) int curmax=0; //过当前这个点的所有直线的最多点数 for(int j=0; j<points.size(); j++){ if(i!=j){ //计算斜率 if(points[i].x==points[j].x && points[i].y==points[j].y){ samepoints++; continue; } //x坐标相同 if(points[i].x==points[j].x){ pointNum[INFTY]++; if(pointNum[INFTY]>curmax)curmax = pointNum[INFTY]; continue; } //x坐标不同 double slop = (points[i].y-points[j].y) * 1.0/(points[i].x-points[j].x); pointNum[slop]++; if(pointNum[slop] > curmax) curmax = pointNum[slop]; } } if(curmax+samepoints > max) max = curmax+samepoints; } return max; }};
0 0
- LeetCode(149)Max Points on a Line
- LeetCode: Max Points on a Line [149]
- LeetCode # 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
- 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)
- 一段代码说明javascript闭包运行机制
- DirectX 教程: DirectX Tutorial - Direct3D: Getting Started
- 修改LINUX系统时间并定时同步
- java transient 串行化
- javascript的prototype经典使用场景
- LeetCode: Max Points on a Line [149]
- 全栈JavaScript之路(七)学习 Comment 类型节点.
- ERROR 1290 (HY000): The MySQL server is running with the --skip-grant-tables option so it cannot exe
- leetcode: Maximal Rectangle
- 如何给ExecutorService异步计算设置超时
- UVA12716 GCD XOR 数论数学构造
- 编程题目:PAT 1007. 素数对猜想 (20)
- 一个新的开始
- 7月风怒