码迷,mamicode.com
首页 > 其他好文 > 详细

Max Points on a line

时间:2014-07-16 20:26:01      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   for   io   div   

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) {}
 * };
 */
class Solution {
public:
    int maxPoints(vector<Point> &points) {
        if(points.size() <= 2){
            return points.size();
        }
        
        map<double,int> slop_lines;
        int maxNumber = 0, same_points, none_slop;
        double slop;
        for(int i = 0; i < points.size()-1; ++i){
            slop_lines.clear();
            same_points = 1;
            none_slop = 0;
            for(int j = i+1; j < points.size(); ++j){
                if(points[i].x == points[j].x &&  points[i].y == points[j].y)
                {
                    ++same_points;
                    continue;
                }
                if(points[i].x == points[j].x){
                    ++none_slop;
                }else{
                    slop = (double)(points[i].y - points[j].y)/(points[i].x - points[j].x);
                    if(slop_lines.find(slop) != slop_lines.end()){
                        ++slop_lines[slop];
                    }else{
                        slop_lines[slop] = 1;
                    }
                }
            }
            
            //更新最大值
            map<double,int>::iterator iter = slop_lines.begin();
            for(;iter != slop_lines.end(); ++iter){
                if(iter->second > none_slop){
                    none_slop = iter->second;
                }
            }
            none_slop += same_points;
            if(none_slop > maxNumber){
                maxNumber=none_slop;
            }
        }
        
        return maxNumber;
    }
};

 

Max Points on a line,布布扣,bubuko.com

Max Points on a line

标签:style   blog   color   for   io   div   

原文地址:http://www.cnblogs.com/awy-blog/p/3568515.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!