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.--------------------- thinking --------------------------
edge cases: 1. empty input 2. same points in the pool!!!!!!!
bugs: when there is only 1 point, the result should be 1. when there are 2 points, the result should be 2!
Remember: INT_MAX
https://oj.leetcode.com/discuss/18590/sharing-my-simple-solution-with-explanation
https://oj.leetcode.com/discuss/24555/c-solution-faster-then-average-c-submission
-------------------- codes ----------------------------------
/**
* 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) {
if (points.size() == 0) return 0;
int max = 1;
for (int i = 0; i < points.size(); i++) {
unordered_map<double, int> abmap;
unordered_map<int, int> xmap;
int same_point = 0;
int local_max = 1;
Point x1 = points[i];
for (int j = i+1; j < points.size(); j++) {
Point x2 = points[j];
if (x1.x == x2.x) {
if (x1.y == x2.y) {
same_point++;
} else if (xmap.find(x1.x) == xmap.end()) {
xmap[x1.x] = 2;
if (local_max < 2) {
local_max = 2;
}
} else {
int num = xmap[x1.x] + 1;
xmap[x1.x] = num;
if (num > local_max) {
local_max = num;
}
}
} else {
double a = double(x1.y - x2.y) / (x1.x - x2.x);
if (abmap.find(a) == abmap.end()) {
abmap[a] = 2;
if (local_max < 2) {
local_max = 2;
}
} else {
int num = abmap[a] + 1;
abmap[a] = num;
if (num > local_max) {
local_max = num;
}
}
}
}
local_max += same_point;
if (max < local_max) {
max = local_max;
}
}
return max;
}
};
No comments:
Post a Comment