[leetcode] Max Points on a Line

题目:


Max Points on a Line

 Total Accepted: 8229 Total Submissions: 80354My Submissions

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

Have you been asked this question in an interview? 

代码如下,已经注释


class Solution {
public:
	int maxPoints(vector<Point> &points)
	{
		if (points.size() == 0) return 0;
		int result = 0; //存储结果
		for (int index = 0; index < points.size(); index++)
		{
			unordered_map<float, int> mp;//使用map也可以,unorder_map是C++ 11加进去的
			int same = 1;//相同的点的数目

			for (int in = 0; in < points.size(); in++)//两次循环便利
			{
				if (index == in) continue;//同一个点,跳过
				if (points[index].x == points[in].x && points[index].y == points[in].y)
				{//假如为座标相同的点(points中有重复数据)
					same++; continue;
				}
				//当斜率正无穷时,使用INT_MAX,FLT_MAX都是可以的
				if (points[index].x == points[in].x) mp[INT_MAX]++;
				else
				{
					float k = ((float)(points[index].y - points[in].y)) / (points[index].x - points[in].x);
					mp[k]++;
				}
			}
			for (std::unordered_map<float, int>::iterator it = mp.begin(); it != mp.end(); it++)
			{//查找最大值
				if (it->second + same > result) result = it->second + same;
			}
			if (same > result) result = same;
		}

		return result;
	}
};


88毫秒通过

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章