首页 > 代码库 > Max Points on a Line
Max Points on a Line
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
参考:http://blog.csdn.net/doc_sgl/article/details/17103427
AC的代码:
#include<iostream>#include<map>#include<vector>#include<set>#include<unordered_map>#include<climits>using namespace std;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) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. unordered_map<float,int> mp; int maxNum = 0; for(int i = 0; i < points.size(); i++) { mp.clear(); mp[INT_MIN] = 0; int duplicate = 1; for(int j = 0; j < points.size(); j++) { if(j == i) continue; if(points[i].x == points[j].x && points[i].y == points[j].y) { duplicate++; continue; } float k = points[i].x == points[j].x ? INT_MAX : (float)(points[j].y - points[i].y)/(points[j].x - points[i].x); mp[k]++; } unordered_map<float, int>::iterator it = mp.begin(); for(; it != mp.end(); it++) if(it->second + duplicate > maxNum) maxNum = it->second + duplicate; } return maxNum; }};int main(){ Solution s; vector<Point> pp= {Point(0,0),Point(0,0),Point(3,10),Point(0,2),Point(0,2),Point(3,10)}; cout<<s.maxPoints(pp)<<endl;}
超时的代码:
#include<iostream>#include<map>#include<vector>#include<set>using namespace std;struct Point{ int x; int y; Point():x(0),y(0) {} Point(int a,int b):x(a),y(b) {}};struct Line{ double k; double t; Line(double a,double b):k(a),t(b) {}};bool operator==(const Point &a,const Point &b){ return a.x==b.x&&a.y==b.y;}bool operator<(const Point &a,const Point &b){ return a.x==b.x?a.y<b.y:a.x<b.x;}bool operator==(const Line &a,const Line &b){ return a.k==b.k&&a.t==b.t;}bool operator<(const Line &a,const Line &b){ return a.k==b.k?a.t<b.t:a.k<b.k;}class Solution{public: int maxPoints(vector<Point> &points) { if(points.empty()||points.size()==1) return points.size(); map<Line,set<Point> > mp; int i,j; int count=0; for(i=0; i<(int)points.size()-1; i++) { for(j=i+1; j<(int)points.size(); j++) { Point x=points[i]; Point y=points[j]; double k; double t; if(x.x==y.x) { k=1e20; t=x.x; } else { k=(y.y-x.y)/(y.x-x.x); t=x.y-x.x*k; } mp[{k,t}].insert(x); mp[{k,t}].insert(y); } } auto start=mp.begin(); while(start!=mp.end()) { cout<<start->first.k<<" "<<start->first.t<<" "<<start->second.size()<<endl; set<Point> st=start->second; multiset<Point> mul(points.begin(),points.end()); auto it=st.begin(); int dup=0; while(it!=st.end()) { dup+=mul.count(*it)-1; it++; } if(count<(int)st.size()+dup) count=st.size()+dup; start++; } return count; }};int main(){ Solution s; vector<Point> pp= {Point(0,0),Point(0,0),Point(3,10),Point(0,2),Point(0,2),Point(3,10)}; cout<<s.maxPoints(pp)<<endl;}
Max Points on a Line
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。