码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode: Max Points on a Line

时间:2015-08-09 20:47:26      阅读:98      评论:0      收藏:0      [点我收藏+]

标签:leetcode

Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.

分析:

任意一条直线都可以表述为

y = ax + b

假设,有两个点(x1,y1), (x2,y2),如果他们都在这条直线上则有

y1 = kx1 +b

y2 = kx2 +b

由此可以得到关系,k = (y2-y1)/(x2-x1)。即如果点c和点a的斜率为k, 而点b和点a的斜率也为k,可以知道点c和点b也在一条线上。

取定一个点points[i], 遍历其他所有节点, 然后统计斜率相同的点数,并求取最大值即可



注意三个地方:

1、如果点的数目小于3个,则最大数目为点的个数。

2、考虑重复点的情况,重复点是无法计算斜率的。

3、考虑直线与y轴平行时,斜率为无穷大的情况。


/**
 * Definition for a point.
 * struct Point {
 *     int x;
 *     int y;
 *     Point() : x(0), y(0) {}
 *     Point(int a, int b) : x(a), y(b) {}
 * };
 */
class Solution {
public:
    int maxPoints(vector<Point> &points) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
		unordered_map<float,int> mp;
		int maxNum = 0;
		for(int i = 0; i < points.size(); i++)
		{
			mp.clear();
			mp[INT_MIN] = 0;
			int duplicate = 1;
			for(int j = 0; j < points.size(); j++)
			{
				if(j == i) continue;
				if(points[i].x == points[j].x && points[i].y == points[j].y)
				{
					duplicate++;
					continue;
				}
				float k = points[i].x == points[j].x ? INT_MAX : (float)(points[j].y - points[i].y)/(points[j].x - points[i].x);
				mp[k]++;
			}
			unordered_map<float, int>::iterator it = mp.begin();
			for(; it != mp.end(); it++)
				if(it->second + duplicate > maxNum)
					maxNum = it->second + duplicate;
		}
		return maxNum;
    }
};



版权声明:本文为博主原创文章,未经博主允许不得转载。

Leetcode: Max Points on a Line

标签:leetcode

原文地址:http://blog.csdn.net/flyljg/article/details/47378649

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!