Max Points on a Line

Total Accepted: 49916 Total Submissions: 365731 Difficulty: Hard

 

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

/**
 * Definition for a point.
 * struct Point {
 *     int x;
 *     int y;
 *     Point() : x(0), y(0) {}
 *     Point(int a, int b) : x(a), y(b) {}
 * };
 */
 
 /*
 输入:
 1.空
 2.一个点、两个点
 3.有多条斜率不存在的点怎么计算
 4.有重复的点怎么计算
 5.一条直线上有多个点

 */
class Solution {
public:
    int maxPoints(vector<Point>& points) {
        int points_size = points.size();
        if(points_size<=2){
            return points_size;
        }

        unordered_map<double,int> slopes;
        int vertical_slopes_points = 0;
        int  max_points = INT_MIN;
        
        for(int i=0;i<points_size;i++){
            int samePoints = 0;
            vertical_slopes_points = 0;
            slopes.clear();
            for(int j=i;j<points_size;j++){
                if(points[i].x==points[j].x && points[i].y==points[j].y){
                    samePoints ++;
                }else if(points[i].x==points[j].x){
                    vertical_slopes_points ++;
                }else{
                    double k = (points[i].y-points[j].y)*1.0/(points[i].x-points[j].x);
                    slopes[k]++;
                }
            }

            if(samePoints == points_size){
                return samePoints;
            }

            vertical_slopes_points += samePoints;
            
            for(auto iter:slopes){
                max_points = max(iter.second+samePoints,max_points);
            }
            
            max_points = max(vertical_slopes_points,max_points);
        }
        return max_points;
    }
};

 

posted @ 2015-12-16 11:38  zengzy  阅读(145)  评论(0编辑  收藏  举报
levels of contents