LeetCode: max-points-on-a-line

题目描述


Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.


找二维图上在同一条直线上最多的点数,这里需要分析的是

1)有重复点的情况

2)在一条直线上的分类,分为斜率可以求的,和斜率不可以求的。

由于斜率可以代表直线的特征,我们这里可以使用斜率来作为键

细节处理:

1、对一个点,两个点的处理;

2、在初始的时候,在一条线上就会是两个点,之后++1;

3、这里计算斜率的时候,用double的数据类型;


具体程序实现:

import java.util.*;
/**
 * Definition for a point.
 * class Point {
 *     int x;
 *     int y;
 *     Point() { x = 0; y = 0; }
 *     Point(int a, int b) { x = a; y = b; }
 * }
 */

public class Solution {
    public int maxPoints(Point[] points) {
        int size=points.length;
        
        //考虑特殊的情况,首先先将点的长度为0和为1的进行排除
        if(size==0)
            return 0;
        else if(size==1)
            return 1;
        
        int ret=0;
        for(int i=0;i<size;i++)
        {
            int curmax=1;
            Map<Double,Integer> mp=new HashMap<>();
            int dup=0;//重复的数量
            int px=0;
            int py=0;
            
            for(int j=0;j<size;j++)
            {
                if(j!=i)
                {
                    double x1=points[j].x-points[i].x;
                    double y1=points[j].y-points[i].y;
                    if((x1==0)&&(y1==0))
                    {
                        dup++;
                    }else if(x1==0)
                        {
                        if(px==0)//第一次直接就是两个点了
                        {
                            px=2;
                        }else{
                            px++;   
                        }
                        curmax=Math.max(curmax,px);
                    }else 
                    {
                        double k=y1/x1;
                        if(mp.get(k) == null) {
                            mp.put(k, 2);
                        }
                        else {
                            mp.put(k, mp.get(k) + 1);
                        }
                        curmax=Math.max(curmax,mp.get(k));//这里需要找这个斜率的和目前的最大值
                    }
                    
                }
                ret=Math.max(ret,curmax+dup);//找这次的最大值加上其重复的点数来替代现在的结果
            }
        } //最外层循环结束后来进行返回
        return ret;
    }
}


猜你喜欢

转载自blog.csdn.net/weixin_30363263/article/details/80682994