LeetCode Max Points on a Line
来源:互联网 发布:知茵女装网上专卖店 编辑:程序博客网 时间:2024/05/16 17:50
Q:
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
该题我的思路是两层循环,根据斜率来判断属于相同一条直线的点有多少个,如果说是在同一条直线上的那么一般在第一轮就得出这条直线所有的点的数量。除了基本思路之外,还需要考虑一些特殊情况,比如可能会输入一些重复的点,或者两个点组成的直线斜率无法计算等等,这些都要考虑进去。
代码:
class Solution{public :int maxPoints(vector<Point> &points){map<double, int> countMap;map<double, int>::iterator it;if(points.empty())return 0;int sameNum;//可能有重复的点int maxNum = 1;//所有点中比int tmpMaxNum = 1;//同一个点所有直线中含有最多的点的个数(同一个点中比)int numOfLine = 1; //同一条横线上斜率无法表示,只有单独计数int temp;for(int i = 0; i < points.size(); i++){countMap.clear();sameNum = 0;numOfLine = 1;tmpMaxNum = 1;double xielv;for(int j = i + 1; j < points.size(); j++){if(i == 3){xielv = 0;}bool flag = false;if(points[i].x == points[j].x && points[i].y == points[j].y){sameNum++;continue;}if((points[j].x != points[i].x))xielv = (double)( points[j].y - points[i].y ) / (double)( points[j].x - points[i].x );else {flag = true;//不计算斜率numOfLine++;}it = countMap.find(xielv);if(!flag)//计算斜率时{if(it != countMap.end()){temp = ++countMap[xielv];}else {countMap[xielv] = 2;//该斜率的直线上的点有2个temp = 2;}if(tmpMaxNum < temp)tmpMaxNum = temp;}if(tmpMaxNum < numOfLine)tmpMaxNum = numOfLine;}if(maxNum < tmpMaxNum + sameNum){maxNum = tmpMaxNum + sameNum;}}return maxNum;}};如果大家有更好的思路,欢迎在评论中提出来,谢谢!
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
- &引用取址
- 读取properties配置文件方法
- 一段文字中替换所有汉字的数字为阿拉伯数字
- stock cluster analysis with graphviz how OEM control automotive company
- STL常见用法整理_set
- LeetCode Max Points on a Line
- C++多重虚拟继承
- C\C++ 内存泄露检测工具
- Gluster vs Ceph:开源存储领域的正面较量
- Android 打包与反编译
- MySQL更新优化
- Oracle SQL性能优化
- 局部变量声明及If……Else
- BCB6 StringGrid操作,写了个乘法口诀