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.
思路
关键是浮点数做key不靠谱,struct hash
代码
/**
* Definition for a point.
* struct Point {
* int x;
* int y;
* Point() : x(0), y(0) {}
* Point(int a, int b) : x(a), y(b) {}
* };
*/
struct Key{
int first;
int second;
Key(int f, int s) : first(f), second(s){};
bool operator==(const Key &other) const{
return first == other.first
&& second == other.second;
}
};
namespace std {
template <>
struct hash<Key>{
size_t operator()(const Key& k) const{
// Compute individual hash values for first,
// second and third and combine them using XOR
// and bit shifting:
return hash<int>()(k.first)
^ (hash<int>()(k.second) << 1);
}
};
}
class Solution {
private:
int calcGCD(int a, int b) {
if (b == 0) //end (divisible, it is the gcd)
return a;
return calcGCD(b, a % b);
}
Key norm(int a, int b) {
int gcd = calcGCD(a, b);
if(gcd == 0) return Key(0,0);//同一个点
return Key(a/gcd, b/gcd);
}
public:
int maxPoints(vector<Point> &points) {
if(points.empty()) return 0;//不然会Input: []; Output: 1
unordered_map<Key, int> nSamelines;
int maxSamelines = 0;
//每次fix一个点,看其他点和它的共线情况
for(int i = 0; i < points.size(); i++){
nSamelines.clear();
nSamelines.emplace(Key(0,0), 1);
for(int j = i+1; j < points.size(); j++){
Key slope = norm(points[i].y-points[j].y, points[i].x-points[j].x);
//if(slope == Key(0,0)) continue;//得看题意了Input:[(0,0),(0,0)] Output:1 Expected:2
auto it = nSamelines.find(slope);
if(it != nSamelines.end()){
it->second += 1;
} else {
nSamelines.emplace(slope, 1);
}
}
if(maxSamelines < nSamelines[Key(0,0)])
maxSamelines = nSamelines[Key(0,0)];
for(auto entry : nSamelines){
if(!(entry.first == Key(0,0)) && (maxSamelines < entry.second + nSamelines[Key(0,0)])) {
maxSamelines = entry.second + nSamelines[Key(0,0)];
}
}
}
return maxSamelines;
}
};