[leetcode] Max Points on a Line
来源:互联网 发布:自动答题软件 编辑:程序博客网 时间:2024/06/05 17:01
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
思路:以每个点为基点,逐个遍历后续点,找出与这个点共线的点的最大个数,注意处理重复的的点,平行x轴,y轴共线的点
/** * 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 len=points.size(); if(len==0) return 0; if(len==1) return 1; if(len==2) return 2; map<double,int> temp;//将斜率保存在map中,以便找到相同斜率点的个数 int maxsum=0,tempsum=0; int samepoint=0; int tmpres=0; int tmp=0; int res=1; int samex=1,samey=1; for(int i=0;i<len;i++){ temp.clear(); for(int j=i+1;j<len;j++){ if(points[j].x==points[i].x){ samex++;//统计与x轴平行的点 } if(points[j].y==points[i].y){ samey++;//统计与y轴平行的点 } double line; if(points[j].x!=points[i].x){ line=1.0*(points[j].y-points[i].y)/(points[j].x-points[i].x);//计算斜率 if(temp.find(line)!=temp.end()){ temp[line]++; tmp=temp[line]; }else{ temp[line]=2; tmp=2; } } else if(points[j].y==points[i].y){ samepoint++;//重复点的个数 continue; } if(tmpres<tmp){ tmpres=tmp; } } if(res<tmpres+samepoint){ res=tmpres+samepoint; } if(res<samex){ res=samex; } if(res<samey){ res=samey; } samepoint=0; samex=1; samey=1; tmpres=0; } return res; }};
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
- Hive权限之审计
- Linux下安装C++开发环境(G++/Eclipse)
- Modelsim仿真查看内部信号
- Linked List part2 : List class
- Mplayer的使用方法
- [leetcode] Max Points on a Line
- 21天学通Java学习笔记-Day09(IO流)
- 删除重复行SQL举例
- 【前端开发】提高网站加载速度
- 寝室空调遥控解码
- Qt5官方demo解析集22——Extending QML - Object and List Property Types Example
- Android配置
- initramfs文件系统制作
- Android入门 在ListView中如何进行精确的定位