Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
/** * 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) { unordered_map<double, int> umap; int res=0; int len=points.size(); if(len>0){ for(int i=0; i<len; ++i){ int samepoints=0; umap.clear(); int tempres=1; for(int j=i+1; j<len; ++j){ double slope=numeric_limits<double>::infinity(); int dx=points[i].x-points[j].x; int dy=points[i].y-points[j].y; if(dx==0){ if(dy==0){ samepoints++; if(res<samepoints) res=samepoints; continue; } } else{ slope=1.0*dy/dx; } if(umap.find(slope)!=umap.end()){ umap[slope]++; } else{ umap.insert(unordered_map<double, int>::value_type(slope, 2)); } if(tempres<umap[slope]) tempres=umap[slope]; } if(res<tempres+samepoints) res=tempres+samepoints; } } return res; } };
LeetCode || Max Points on a Line,布布扣,bubuko.com
LeetCode || Max Points on a Line
原文:http://blog.csdn.net/jiadebin890724/article/details/23303115