2019独角兽企业重金招聘Python工程师标准>>>
Max Points on a Line
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
题目是:在2D平面内给N个点,求最多多少个点在一个直线上.
以下是AC的解决方式:
/*** 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) {Point p1,p2;int max_point = 0;for (int i = 0; i < points.size() - max_point; ++i){p1 = points.at(i);// 第一个点//这个地方一开始没有减max_point是超时的,减了之后就AC了for (int j = i + 1; j < points.size() - max_point; ++j){Point temp = points.at(j);//第二点已经找到if (p1.x != temp.x || p1.y != temp.y){p2 = temp;int maxp = 0;for (int k = 0; k < points.size(); ++k){Point p3 = points.at(k);// 和p1相同,和p2相同,和p1,p2在同一直线if ((p3.x == p1.x && p3.y == p1.y) || (p3.x == p2.x && p3.y == p2.y) || ((p3.x - p2.x) * (p1.y - p2.y)) == ((p3.y - p2.y) * (p1.x - p2.x))){maxp ++;}}if (maxp > max_point){max_point = maxp;}}}}if (max_point == 0){max_point = points.size();}return max_point;}
};
题目链接:
https://oj.leetcode.com/problems/max-points-on-a-line/