Max Points on a Line
生活随笔
收集整理的這篇文章主要介紹了
Max Points on a Line
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
Given?n?points on a 2D plane, find the maximum number of points that lie on the same straight line.
需考慮3類特殊情況:1、x1=x2,斜率無窮大;2、x1=x2,y1=y2,相同點(diǎn)也要計(jì)數(shù),當(dāng)計(jì)算最終結(jié)果時(shí)要加上該值,且相同點(diǎn)個(gè)數(shù)初始化為1,即其本身;3、y1=y2;
計(jì)算斜率時(shí)(double)(points[j].y-points[i].y)/(points[j].x-points[i].x)和(double)((points[j].y-points[i].y)/(points[j].x-points[i].x))結(jié)果不同,需注意。
1 /** 2 * Definition for a point. 3 * struct Point { 4 * int x; 5 * int y; 6 * Point() : x(0), y(0) {} 7 * Point(int a, int b) : x(a), y(b) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 int maxPoints(vector<Point>& points) { 13 int n=points.size(); 14 if(n<3) return n; 15 int res=0; 16 map<double,int> mp; 17 for(int i=0;i<n-1;i++) 18 { 19 int samepoint=1; 20 int maxpoint=0; 21 int samex=0; 22 23 mp.clear(); 24 map<double,int>::iterator it; 25 for(int j=i+1;j<n;j++) 26 { 27 double slope=0.0; 28 if(i==j) 29 continue; 30 if(points[i].x==points[j].x) 31 { 32 if(points[i].y==points[j].y) 33 samepoint++; 34 else 35 { 36 samex++; 37 maxpoint=max(maxpoint,samex); 38 } 39 continue; 40 } 41 42 43 if(points[i].y==points[j].y) 44 slope=0.0; 45 else 46 slope=(double)(points[j].y-points[i].y)/(points[j].x-points[i].x); 47 it=mp.find(slope); 48 if(it!=mp.end()) 49 it->second+=1; 50 else 51 mp.insert(pair<double,int>(slope,1)); 52 if(mp[slope]>maxpoint) //if(it->second>maxpoint) 53 maxpoint=mp[slope]; //maxpoint=it->second; 結(jié)果錯(cuò)誤,為6452609,即it=mp.end(),空指針。 54 } 55 maxpoint+=samepoint; 56 res=max(res,maxpoint); 57 } 58 return res; 59 } 60 };?
總結(jié)
以上是生活随笔為你收集整理的Max Points on a Line的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 创建Windows类别
- 下一篇: 自定义AlertDialog 问自己的单