这个设计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;
}