• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
ArgenBarbie
博客园    首页    新随笔    联系   管理    订阅  订阅
149. Max Points on a Line *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) {}
 * };
 */
class Solution {
public:
    int maxPoints(vector<Point>& points) {
        int n = points.size(), i, j, ans = 0;
        if(1 == n)
            return 1;
        for(i = 0; i < n; i++)
        {
            map<double, int> m;
            map<int, int> x, y;
            int samePoint = 0;
            for(j = 0; j < n; j++)
            {
                int deltaX = points[i].x - points[j].x;
                int deltaY = points[i].y - points[j].y;
                if(0 == deltaX && 0 == deltaY)
                {
                    samePoint++;
                }
                else if(0 == deltaX)
                {
                    if(x.find(points[i].x) == x.end())
                        x[points[i].x] = 1;
                    else
                        x[points[i].x]++;
                }
                else if(0 == deltaY)
                {
                    if(y.find(points[i].y) == y.end())
                        y[points[i].y] = 1;
                    else
                        y[points[i].y]++;
                }
                else
                {
                    double t = 1.0 * deltaX / deltaY;
                    if(m.find(t) == m.end())
                        m[t] = 1;
                    else
                        m[t]++;
                }
            }
            ans = max(ans, samePoint);
            for(map<double, int>::iterator it = m.begin(); it != m.end(); it++)
                ans = max(ans, it->second+samePoint);
            for(map<int, int>::iterator it = x.begin(); it != x.end(); it++)
                ans = max(ans, it->second+samePoint);
            for(map<int, int>::iterator it = y.begin(); it != y.end(); it++)
                ans = max(ans, it->second+samePoint);
        }
        return ans;
    }
};

 

posted on 2016-08-20 21:50  ArgenBarbie  阅读(163)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3