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.
需考虑3类特殊情况:1、x1=x2,斜率无穷大;2、x1=x2,y1=y2,相同点也要计数,当计算最终结果时要加上该值,且相同点个数初始化为1,即其本身;3、y1=y2;
计算斜率时(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))结果不同,需注意。
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; 结果错误,为6452609,即it=mp.end(),空指针。 54 } 55 maxpoint+=samepoint; 56 res=max(res,maxpoint); 57 } 58 return res; 59 } 60 };
联系方式:emhhbmdfbGlhbmcxOTkxQDEyNi5jb20=
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了