Wednesday, September 17, 2014

[Leetcode] Max Points on a Line

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

Analysis:

Points are on the same straight line they have the same slope. Use a hash table to accumulate all slopes for every pair of points. 


Note: special case:
1. slope could be infinite if two points have the same x value.
2. duplicate points

/**
 * 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) {
        
        int maxPoints = 0;
        for(int i=0; i < points.size(); i++)
        {
            int samePoints = 0;
            int infinite = 0;
            map<double, int> m;
            for(int j=i + 1; j < points.size(); j++)
            {
                if (points[j].y == points[i].y && points[j].x == points[i].x)
                    samePoints++;
                else if (points[j].x == points[i].x)
                    infinite++;
                else
                {
                    double slope = 1.0 * (points[j].y - points[i].y) / (points[j].x - points[i].x);
                    m[slope]++;
                }
            }
            
            int points = 0;
            for(map<double, int>::iterator itr = m.begin(); itr != m.end(); itr++)
            {
                points = max(points, itr->second);
            }
            
            points = max(points, infinite);
            maxPoints = max(maxPoints, points + 1 + samePoints);
            
        }
        return maxPoints;
    }
};

No comments:

Post a Comment