這個設計test case是個好題目。本來的想法是以斜率爲key,做hashtable計數,試了幾次行不通。似乎改造下這個方案也是可行的。
後來乾脆按照line來計數。最主要的是點重複這個事情不好弄,乾脆吧點集預處理下。發現leetcode論壇裏有個類似的思路,不過那個解法錯了。
代碼有點醜,如下:
struct Point {
int x;
int y;
Point() : x(0), y(0) {}
Point(int a, int b) : x(a), y(b) {}
};
struct Line {
double s;
double t;
Line(Point a, Point b){
if (a.x==b.x){
s = numeric_limits<double>::max();
t = a.x;
}
else{
s = (b.y*1.0 - a.y) / (b.x-a.x);
t = a.y - a.x*s;
}
}
};
bool operator<(const Line& a, const Line& b){
return a.s == b.s ? a.t < b.t : a.s < b.s;
}
bool operator<(const Point&a, const Point& b){
return a.x == b.x ? a.y < b.y : a.x < b.x;
}
map<Point, int>::iterator insertOrUpdate(map<Point, int>& m, Point p){
auto it = m.find(p);
if (it==m.end()){
auto res = m.insert(make_pair(p, 1));
it = res.first;
}
else{
it->second++;
}
return it;
}
map<Line, int>::iterator insertOrUpdate(map<Line, int>& m, Line l, int count){
auto it = m.find(l);
if (it == m.end()){
auto res = m.insert(make_pair(l, count));
it = res.first;
}
else{
it->second+=count;
}
cout << it->second << endl;
return it;
}
int maxPoints(vector<Point> &points) {
if (points.size()==1){
return 1;
}
map<Point, int> pCount;
set<Point> pSet;
int result = 0;
for (auto& i:points){
auto it = insertOrUpdate(pCount, i);
pSet.insert(i);
result = max(result, it->second);
}
map<Line, set<const Point*>> lineMap;
for (auto i = pSet.begin(); i != pSet.end(); ++i){
auto j = i;
j++;
for (; j != pSet.end(); ++j){
Line line(*i, *j);
lineMap[line].insert(&(*i));
lineMap[line].insert(&(*j));
}
}
for (auto& i:lineMap){
int tmp = 0;
for (auto& j:i.second){
tmp += pCount[*j];
}
result = max(result, tmp);
}
return result;
}