Find the maximum number of points that a straight line passes through

Source: Internet
Author: User

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

Analysis: Fixed a point, traversing the remaining points, the period with a HashMap record two points slope and the number of slopes, the local maximum value, and then fixed another point, traversing the rest, ..., that is, two loops, the inner loop to find the local maximum value, the outer loop to update the global maximum value. Need to note: 1. The point overlap Case 2. The case of a straight line perpendicular to the X axis 3. Normal condition 4. Conditions with a slope of-0.0

Java code:

     Public intmaxpoints (point[] points) {if(Points.length <= 2) {            returnpoints.length; }        intMax = 0; floatK =0f;  for(inti = 0; i < points.length-1; i++) {//Global Maximum ValueHashmap<float, integer> HM =NewHashmap<float, integer>(); Hm.put (Float.max_value,0); intRepoint = 0;  for(intj = i+1; J < Points.length; J + +) {//local maximum, fixed one point                if(points[i].x = = points[j].x && points[i].y = = points[j].y) {//Dot Coincidentrepoint++; }                Else if(points[i].x = = points[j].x) {//Vertical X-axisHm.put (Float.max_value, Hm.get (float.max_value) +1); }                Else{k= (float) (POINTS[I].Y-POINTS[J].Y)/(points[i].x-points[j].x);//Normal situation                    if(k = =-0.0) {//appears -0.0K =0f; }                    if(!Hm.containskey (k)) {hm.put (k,1); } Else{hm.put (k, Hm.get (k)+1); }                }            }             for(Float d:hm.keyset ()) {if(Hm.get (d) +repoint+1 >max) {Max= Hm.get (d) +repoint+1; }            }        }        returnMax; }

Find the maximum number of points that a straight line passes through

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.