@zimenglan
2014-11-29T11:23:12.000000Z
字数 1171
阅读 1143
leetcode
题目大意:
给定一些点(二维)的集合, 找出位于同一条直线的点的个数的最大值
Code
reference
/*** 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) {double slope;int maxNum = 0;double nSlope;int size = points.size();// if the number of the points is less than 3// then directly return it// since more than 1 point makes a lineif(size < 3) {return size;}for(int i = 0; i < size; i++) {int rep = 0;// slope -> countstd::map<double, int> lines;for(int j = 0; j < size; j++) {if(i == j) {continue;}// replicationif(points[i].x == points[j].x&& points[i].y == points[j].y) {rep++;continue;}// x1 == x2// in this case, it can compute the slope// which is oo (infinity)// so use INT_MIN or INT_MAX to record this case// here use INT_MINif(points[i].x == points[j].x) {lines[INT_MIN]++;} else {slope = (points[i].y - points[j].y)/ (points[i].x - points[j].x + 0.);lines[slope]++;}}// statistic & maybe lines is emptyif(lines.size() == 0) {maxNum = max(maxNum, rep);continue;}// statisticstd::map<double, int>::iterator iter;for(iter = lines.begin(); iter != lines.end(); iter++) {if(iter->second + rep > maxNum) {maxNum = iter->second + rep;nSlope = iter->first;}}}// don't forget that plus the point itselfreturn maxNum + 1;}};