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

LeetCode Max Points on a Line

时间:2015-04-17 21:45:48      阅读:110      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!