careercup-Mathematics and Probability 7.6

Source: Internet
Author: User

7.6 on the two-dimensional plane, there are some points, please find the line that passes the most points.

Solution:

Similar to Leetcode:max Points on a line

We only need to "draw" an infinitely long line (not a line segment) between any two points, and use the hash list to track which line appears most often. The time complexity of this practice O (n^2), because there are altogether n^2 line segments.

By using each point with a slope other than itself (to note the absence of equality and slope), use Unorder_map to insert a K-value and accumulate the same K-value, adding one point to the line at a time. The main idea is that any point on a straight line is equal to the K value obtained from the other points, so you can calculate the number of points on the slope by calculating the slope at any point with each other.

C + + Implementation code:

#include <iostream>#include<unordered_map>#include<vector>#include<climits>using namespacestd;structpoint{intx; inty; Point (): X (0), Y (0) {} point (intAintb): X (a), Y (b) {}};intMaxpoints (Vector<point> &points) {    if(Points.empty ())return 0; intn=points.size (); inti,j; intmaxnum=0; Unordered_map<Double,int>MP;  for(i=0; i<n;i++)    {        intDuplicate=1; Mp[int_max]=0;        Mp.clear ();  for(j=0; j<n;j++)        {            if(i==j)Continue; if(points[i].x==points[j].x&&points[i].y==points[j].y) {Duplicate++; Continue; }            DoubleK= (Points[i].x==points[j].x?int_max: (Double) (POINTS[I].Y-POINTS[J].Y)/(points[i].x-points[j].x)); MP[K]++; } Auto Mp_iter=Mp.begin ();  while(mp_iter!=Mp.end ()) {            if(mp_iter->second+duplicate>maxnum) Maxnum=mp_iter->second+Duplicate; Mp_iter++; }    }    returnMaxnum;}intmain () {vector<Point> Vec={point (0,0), point (1,1), point (2,2), point (388,4), point (6,3), point (0,0)}; cout<<maxpoints (VEC) <<Endl;}

careercup-Mathematics and Probability 7.6

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.