枚举任意两个点,然后看其他点是否落在他俩形成的直线上,方法就是看斜率是否相等,斜率相等的两个直线可能平行或重合,因为我们这里是三个点,所以肯定重合。其实这题暴力也能过
class Solution {
public:
int maxPoints(vector<vector<int>>& points) {
int n = points.size();
if(n == 1)
return 1;
int ans = 0;
for(int i = 0; i < n; i++){
vector<int> a = points[i];
for(int j = i+1; j < n; j++){
vector<int> b = points[j];
int count = 2;
for(int k = j+1; k < n; k++){
vector<int> c = points[k];
if((b[1]-a[1])*(c[0]-b[0]) == (b[0]-a[0])*(c[1]-b[1])){
count++;
}
}
ans = max(ans, count);
}
}
return ans;
}
};
答案是对于每一个点,计算其他所有点与它的斜率,斜率相同的在同一条直线上,利用哈希表存储斜率。注意斜率不存在的情况(在一条横线上或者有点重合)