首页 > 其他 > 详细

LeetCode Max Points on a Line

时间:2015-04-17 21:43:48      阅读:159      评论:0      收藏:0      [点我收藏+]

题目如下:

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) {
    int answer = 0;
    for(int i = 0; i < points.size(); i++){
        int samePoint = 1;
        unordered_map<double, int> map;
        for(int j = i + 1; j < points.size(); j++){
            if(points[i].x == points[j].x && points[i].y == points[j].y){
                samePoint++;
            }
            else if(points[i].x == points[j].x){
                map[INT_MAX]++;
            }
            else{
                double slope = double(points[i].y - points[j].y) / double(points[i].x - points[j].x);
                map[slope]++;
            }
        }
        int localMax = 0;
        for(unordered_map<doubleint>::iterator it = map.begin(); it != map.end(); it++){
            localMax = max(localMax, it->second);
        }
        localMax += samePoint;
        answer = max(result, localMax);
    }
    return answer;
}
};

话说有没有更快的算法?

LeetCode Max Points on a Line

原文:http://www.cnblogs.com/asawanggaa/p/4435918.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!