# [leetcode] 149. 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.

1. 题目没有说明所有点不重复，可能有重复的点；

2. 平行y轴的直线没有斜率，不能存入HashTable，要特殊处理。

/**
* 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) {
int maxNum = 0;

if(points.size() == 0) return 0;
if(points.size() == 1) maxNum = 1;

for(int i=0; i<points.size(); i++) {
unordered_map<double, int> hash;
int sameX = 0;    //e.g. line x=5
int samePoint = 1;
for(int j=i+1; j<points.size(); j++) {
if(points[i].x == points[j].x && points[i].y == points[j].y) {
samePoint++;
}
else if(points[i].x == points[j].x) {
sameX++;
}
else {
double k = (double)(points[j].y - points[i].y) / (double)(points[j].x - points[i].x);
if(hash.find(k) == hash.end()) hash[k] = 1;
else hash[k]++;
}
}
for(auto it = hash.begin(); it != hash.end(); it++) {
maxNum = max(maxNum, it->second + samePoint);
}
maxNum = max(maxNum, sameX + samePoint);
}

return maxNum;
}
};

#### Leetcode 149. Max Points on a Line

2016-04-29 10:38:12

#### [Leetcode]149. Max Points on a Line @python

2016-02-05 14:06:11

#### [leetcode] 149. Max Points on a Line 解题报告

2016-05-15 14:24:37

#### Max Points on a Line -- LeetCode

2014-03-14 00:45:59

#### [leetcode]149. Max Points on a Line@Java解题报告

2017-08-01 13:42:39

#### 【LeetCode】149. Max Points on a Line - javascript

2017-08-06 10:56:48

#### Leetcode: Max Points on a Line

2013-12-03 22:57:09

#### LeetCode(149)Max Points on a Line

2014-03-07 13:49:08

#### 【LeetCode】Max Points on a Line 解题报告

2014-08-28 22:05:38

#### 【LeetCode with Python】 Max Points on a Line

2014-09-21 17:41:21