mardi 28 janvier 2020

Explanation and complexity for visible points in codefight

I came across this question on code fight/code signal Given an array of points on a plane find the maximum no of points that are visible from the origin with a viewing angle of 45 degrees.

int visiblePoints(std::vector<std::vector<int>> points) {


const double pi=M_PI,pi_45=M_PI_4,pi_360=M_PI*2.0;
const double epsilon=1e-10;
int n=points.size(),result=0;
vector<double> angles(n);
for(int i=0;i<n;i++){
    double angle=atan2(points[i][1],points[i][0]);
    angles[i]=angle;
    if(angle<pi_45-pi){
        angles.push_back(angle+pi_360);
    }
}
sort(angles.begin(),angles.end());
//std::sort(angles.begin(), angles.end());
for(auto it=angles.begin();it!=angles.begin()+n;++it){
    auto bound=upper_bound(it,angles.end(),*it+(pi_45+epsilon));
    int curr=distance(it,bound);
    if(curr>result){
        result=curr;
    }
}
return result;
/*
for (auto it = angles.begin(), e = angles.begin() + n; it != e; ++it) {
    auto bound = std::upper_bound(it, angles.end(), *it + (pi_over_4 + epsilon));
    int cur = std::distance(it, bound);
    if (cur > result)
        result = cur;
}
return result;
*/

So the code is fine,I can figure out what is happening here.I just wanted to check is the time complexity O(NlogN). The first for loop takes O(N).points is an array of several points in 2D.For example points =[[1,1],[3,1],.....] Then we have the sorting part. I am assuming that sort takes O(N*logN). Of course, quick sort in worst case takes O(N^2), but for now, I will ignore that fact. And then the last loop is again O(N) Also, will the space complexity in this scenario be O(1) or O(N)(due to the sorting) Thank you

Aucun commentaire:

Enregistrer un commentaire