LeetCode---3.Max Points on a Line

題目鏈接:https://oj.leetcode.com/problems/max-points-on-a-line/

解題思路:

任取一點,求該點與其他所有點的斜率,擁有相同斜率的點處於同一直線上,計算這些點的數量。遍歷所有的點,排序得出最大的點數。

代碼:

#ifndef MAXPOINTONLINE_H_
#define MAXPOINTONLINE_H_

#include "header.h"

#pragma once

const double INF = 210000000;

struct Point {
	int x;
	int y;
	Point() : x(0), y(0) {}
	Point(int a, int b) : x(a), y(b) {}
};


class MaxPointOnLine
{
public:
	int maxPoints(vector<Point> &points) {
		max_num = 1;
		int same_point = 0;
		vector<Point>::iterator iteri;
		vector<Point>::iterator iterj;
		if (points.size() <= 2) {
			return points.size();
		}
		for (iteri = points.begin(); iteri != points.end(); iteri ++) {
			Point p = *iteri;
			k.clear();
			same_point = 0;
			for (iterj = iteri + 1; iterj != points.end(); iterj ++) {
				if (iteri->x == iterj->x) {
					if (iteri->y == iterj->y) {
						same_point++;
					}
					else {
						k.push_back(INF);
					}
					
				}
				else {
					k.push_back(double(iteri->y - iterj->y) / (iteri->x - iterj->x));
				}
			}
			int count = 1;
			if (k.size() == 0) {
				count += same_point;
				max_num = (max_num < count) ? count : max_num;
			}
			else if (k.size() == 1) {
				count += (same_point+1);
				max_num = (max_num < count) ? count : max_num;
			} 
			else if( k.size() > 1){
				std::sort(k.begin(), k.end(), compare);
				vector<double>::iterator iter;
				for ( iter = k.begin(); iter < k.end()-1; iter++) {
					if (*iter == *(iter + 1)) {
						count++;
					}
					else {
						count += (same_point + 1);
						max_num = (max_num < count) ? count : max_num;
						count = 1;
					}
				}
				if (count > 1) {
					count += (same_point + 1);
					max_num = (max_num < count) ? count : max_num;
				}
			}
		}
		return max_num;
	}
private:

	static bool compare(const double& c1, const double& c2) {
		return c1 < c2;
	}
	vector<double> k;
	int max_num;
};


#endif


發佈了31 篇原創文章 · 獲贊 27 · 訪問量 11萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章