[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毫秒通過

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