Max Points on a Line
来源:互联网 发布:火影忍者服装淘宝网 编辑:程序博客网 时间:2024/06/05 17:10
题目:Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
思路:hash表
首先一个方法就是hash内容是斜率和个数
从前往后判断,计算每一个点的斜率,当然需要首先判断是否垂直点,是否同一个点,然后再hash[slope],随时输出最大值,这个只是代表了非同一个点。
还需要加上相同点。接下来还需要和垂直点个数比较。
代码:
/** * 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) { if(points.empty()) return 0; int n=points.size(); int result=0; for(int i=0;i<n;i++){ unordered_map<double,int> counter; int same=1; int ver=1; int maxCount=0; for(int j=i+1;j<n;j++){ if(points[i].x==points[j].x&&points[i].y==points[j].y){ //这个时候是同一个点 same++; ver++; }else if(points[i].x==points[j].x){ ver++; }else{ double slope=1.0*(points[i].y-points[j].y)/(points[i].x-points[j].x); //这个地方不写1.0*....就是错误啊 ++counter[slope]; if(counter[slope]>maxCount) maxCount=counter[slope]; } } maxCount+=same; if(maxCount<ver) maxCount=ver; if(maxCount>result) result=maxCount; } return result; }};
0 0
- Max Points on a Line
- Max Points on a Line
- Max Points on a Line
- Max Points on a Line
- Max Points on a Line
- Max Points on a Line
- Max Points On a Line
- Max Points on a Line
- Max Points on a Line
- Max Points on a Line
- max points on a line
- Max Points on a Line
- Max Points on a Line
- Max Points on a Line
- Max Points on a Line
- Max Points on a Line
- Max Points on a Line
- Max Points on a Line
- SpringMVC-----8、SpringMVC上传文件
- hihocoder 1157 : 建造金字塔
- 不不不!我要认真写博客!--Django的安装
- SpringMVC-----9、SpringMVC拦截器
- Android新手学习笔记-startActivity(intent);
- Max Points on a Line
- IOS 001 关于storyboard的第一次使用
- SpringMVC-----10、SpringMVC和Spring集成
- Java之线程的创建简述
- 使用两个栈实现一个队列
- JS setInterval()、 setInterval()与 clearInterval() 方法的使用
- AI初步
- HashSet去重
- Android Animation各种动画详解