您的位置:首页 > 其它

[LeetCode OJ] Max Points on a Line 解题报告

2014-08-27 03:42 288 查看
写了半天结果被撤销了。那就偷懒直接贴代码了。

/**
* Definition for a point.
* struct Point {
*     int x;
*     int y;
*     Point() : x(0), y(0) {}
*     Point(int a, int b) : x(a), y(b) {}
* };
*/
#include <iostream>
#include <stack>
#include <string>
#include <vector>
#include <cstdlib>
#include <tr1/unordered_map>
#define INF 0x7fffffff
class Solution {
public:
int maxPoints(vector<Point> &points) {
unordered_map<double,int> umap;
unordered_map<double,int>::iterator it;
int ans = 1;
int size =points.size();
if(size == 0)
ans=0;
for(int i=0; i<size; ++i){
int sameCnt = 1;
umap.clear();
for(int j=i+1; j<size; ++j){
double key;
if(points[i].x == points[j].x && points[i].y == points[j].y){
++sameCnt;
continue;
}
else if(points[i].x == points[j].x){
key = INF;
}
else{
key = (double)(points[j].y-points[i].y)/(double)(points[j].x-points[i].x);
}
it = umap.find(key);
if(it == umap.end()){
umap[key] = 1;
}
else{
umap[key]++;
}
}
ans = max(ans,sameCnt);//多点重合的情况,umap为空
for(it = umap.begin(); it != umap.end(); ++it){
ans = max(ans,it->second+sameCnt);
}
}
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: