Leetcode: max-points-on-a-line

来源:互联网 发布:淘宝学生家代购 编辑:程序博客网 时间:2024/06/06 03:02

题目:

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


分析:

题目是给定一个二维平面上的点,希望求得这个平面上经过最多点的直线经过了多少个点。解这个题目需要用到穷举的思想,即计算每个点到其他点的斜

率,如果斜率相同,则共线。按照这个思路我们可以创建一个键为double,值为int类型的HashMap,穷举每两个点之间的斜率时,判断HashMap中是否

存在该斜率,没有就创建这个斜率的键值对,有就将值加1。需要考虑与该点重合还有垂直的情况。


具体代码如下:


/** * Definition for a point. * class Point { *     int x; *     int y; *     Point() { x = 0; y = 0; } *     Point(int a, int b) { x = a; y = b; } * } */import java.util.HashMap;public class Solution {    public int maxPoints(Point[] points) {    int len = points.length;                if (len < 2)            return len;                                                int ret = 0;        for (int i = 0; i < len; i++){            int chuizhi = 0;        int chonghe = 1;            HashMap<Double, Integer> hm = new HashMap<Double, Integer>();            for (int j = 0; j < len; j++){                if (i == j)                    continue;                else{                    int diffX = points[i].x - points[j].x;                    int diffY = points[i].y - points[j].y;                                        if (diffX == 0 && diffY == 0){                        chonghe++;                    }                    else if (diffX == 0){                        chuizhi++;                    }                    else{                        double slope = diffY*1.0/diffX;                        if (hm.get(slope) == null){                            hm.put(slope, 1);                        }                        else{                            hm.put(slope, hm.get(slope)+1);                        }                                            }                }                            }                        int max = chuizhi;            for(double k : hm.keySet()){                max = Math.max(max, hm.get(k));            }                        ret = Math.max(ret, max+chonghe);        }                return ret;    }        }


原创粉丝点击