leetcode max points on a line

问题描述

对于给定的n个位于同一二维平面上的点,求最多能有多少个点位于同一直线上
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
输入的point的结构为:

 * struct Point {
 *     int x;
 *     int y;
 *     Point() : x(0), y(0) {}
 *     Point(int a, int b) : x(a), y(b) {}
 * };
 */

解决方案

这题基本的框架是穷举:针对每个点,穷举剩下的点的所有可能性。
有几点是这道问题中需要注意的:

  • 使用斜率作为一条直线上的所有可能性的穷举。应当考虑斜率为无穷(垂直情况)和两点重合情况。
  • 计算斜率时float和double可能出现精度不够或出现无穷小数的情况,这样在使用斜率的map时会出现问题(一开始使用double计算斜率有几例不能通过)。使用斜率的分子分母公约数pair对替代斜率作为map的key可以避免小数计算时的问题。map定义为map<map<int,int>,int>。
#include <vector>
#include <algorithm>
#include <map>
class Solution {
public:
    int maxPoints(vector<Point> &points) {
        int size = points.size();
        int max_count=0;
        if(size==0)return 0 ;
        if(size==1)return 1;
        for(int i = 0;i<size;i++){
            int x_temp=points[i].x,y_temp=points[i].y;
            int count_row=0,extra_count=0;
            int max_temp=0;
            map<map<int,int>,int>k;
            for(int j=0;j<points.size();j++){
                int x = points[j].x,y=points[j].y;
                if(x==x_temp&&y==y_temp){
                    extra_count++;
                    max_temp=max(max_temp,extra_count);
                }
                else {
                    if(x==x_temp && y!=y_temp){
                        count_row++;
                        max_temp = max(max_temp,count_row+extra_count);
                    }
                    else{
                        int gapx= x-x_temp;
                        int gapy = y-y_temp;
                        map<int,int>k_temp;
                        int d = std::__gcd(gapx,gapy);
                        k_temp[gapy/d]=gapx/d;
                        map<map<int,int>,int>::iterator iter;
                        iter = k.find(k_temp);
                        if(iter==k.end()){
                            k[k_temp]=1;
                        }
                        else{
                            k[k_temp]++;
                         
                        }
                        max_temp=max(max_temp,k[k_temp]+extra_count);
                    }
                }
            }
            max_count=max(max_count,max_temp);
        }
        return max_count;
    }
    
    
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值