(very simple logic question)
Question:
You are given an array points, where points[i] = [xi, yi] represents a point on the XY plane. Find the maximum number of points on the same line.
Problem solution:
only need to consider starting from each point, how many points at most are on the same straight line
Then directly traverse each other point and calculate the slope of each other point and the current point to
see the highest value with the same slope
How to save the slope, there is a problem with decimal precision, then save the fraction (the numerator and denominator need to be divided)
and then use a map to store the same amount of slope, that is, map<pair<int, int>, int>
code show as below:
class Solution {
public:
int gcd(int a, int b) {
return a % b == 0 ? b : gcd(b, a % b);
}
vector<pair<int, int> > points_temp;
int maxPoints(vector<vector<int>>& points) {
for(int i = 0; i < points.size(); i++) {
points_temp.push_back(make_pair(points[i][0], points[i][1]));
}
sort(points_temp.begin(), points_temp.end());
int res = 1;
map<pair<int, int>, int> temp;
for(int i = 0; i < points_temp.size(); i++) {
temp.clear();
for(int j = i + 1; j < points_temp.size(); j++) {
int x = points_temp[j].first - points_temp[i].first;
int y = points_temp[j].second - points_temp[i].second;
if(x == 0) {
y = 1;
}
else if(y == 0) {
x = 1;
}
else {
int t = gcd(x, y);
x = x / t;
y = y / t;
}
pair<int, int> p = make_pair(x, y);
if(temp.count(p) == 0) {
temp[p] = 2;
}
else {
temp[p] = temp[p] + 1;
}
res = max(res, temp[p]);
}
}
return res;
}
};