LeetCode: Max Points on a Line

16 篇文章 0 订阅

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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值