Tuesday, December 23, 2014

Max Points on a Line

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

T:
For each point, look at its following points one by one. Use a hashmap to count the number of points that has the same slope. The slope with max number of count should be the answer for current point. If there is a point that overlaps the current point, we need to add it to the count for each slope we see.

A:

/**
 * 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) {
        if(points.size() < 3) {
            return points.size();
        }
        int max = 0;
        for(int i=0; i < points.size(); i++) {
            map< double, int > count;
            int plus = 0;
            int nx = 1;
            for(int j=i+1; j < points.size(); j++) {
                double dx = points[i].x - points[j].x;
                double dy = points[i].y - points[j].y;
                if (dx == 0 && dy == 0) {
                    plus++;
                } else if (dx == 0) {
                    nx++;
                } else {
                    double slop = dy/dx;
                    count[slop]++;
                }
            }
            int tmp = nx;
            for(auto m : count) {
                if (m.second + 1 > tmp) {
                    tmp = m.second + 1;
                }
            }
            tmp += plus;
            if(tmp > max) {
                max = tmp;
            }
        }
        return max;
    }
};

No comments:

Post a Comment