Below is the solution I am trying to implement
/**
* Definition for a point.
* class Point {
* int x;
* int y;
* Point() { x = 0; y = 0; }
* Point(int a, int b) { x = a; y = b; }
* }
*/
public class Solution {
public int maxPoints(Point[] points) {
int max=0;
if(points.length==1)
return 1;
for(int i=0;i<points.length;i++){
for(int j=0;j<points.length;j++){
if((points[i].x!=points[j].x)||(points[i].y!=points[j].y)){
int coll=get_collinear(points[i].x,points[i].y,points[j].x,points[j].y,points);
if(coll>max)
max=coll;
}
else{
**Case where I am suffering**
}
}
}
return max;
}
public int get_collinear(int x1,int y1,int x2, int y2,Point[] points)
{
int c=0;
for(int i=0;i<points.length;i++){
int k1=x1-points[i].x;
int l1=y1-points[i].y;
int k2=x2-points[i].x;
int l2=y2-points[i].y;
if((k1*l2-k2*l1)==0)
c++;
}
return c;
}
}
It runs at O(n^3). What I am basically doing is running two loops comparing various points in the 2d plane. And then taking 2 points I send these 2 points to the get_collinear method which hits the line formed by these 2 points with all the elements of the array to check if the 3 points are collinear. I know this is a brute force method. However in case where the input is[(0,0),(0,0)] my result fails. The else loop is where I have to add a condition to figure out such cases. Can someone help me with the solution to that. And does there exist a better solution to this problem at better run time. I can't think of any.
BTW complexity is indeed
O(n^3)
to lower that you need to:sort the points somehow
by
x
and ory
in ascending or descending order. Also use of polar coordinates can help sometimesuse divide at impera (divide and conquer) algorithms
usually for planar geometry algorithms is good idea to divide area to quadrants and sub-quadrants but these algorithms are hard to code on vector graphics
Also there is one other speedup possibility
check against all possible directions (limited number of them for example to
360
angles only) which leads toO(n^2)
. Then compute results which is stillO(m^3)
wherem
is the subset of points per the tested direction.Ok here is something basic I coded in C++ for example:
It is from my geometry engine so here is some stuff explained:
glview2D::_pnt
view.pnt[]
are input 2D points (I feed random points around random line + random noise points)view.pnt.num
is number of pointsglview2D::_lin
view.lin[]
are output lines (just one line is used)accuracy
Play with
pacc,lmin,lmax
constants to change the behavior and computation speed. Changedirs
to change direction accuracy and computation speedComplexity estimation is not possible due to big dependency on input data
But for my random test points are the runtimes like this: