#leetcode#Max Points on a Line

来源:互联网 发布:强制刷机软件 编辑:程序博客网 时间:2024/04/27 19:17

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

Hide Tags
 Hash Table Math





Hard题目其实也是难了不会, 会了不难。。。
分析见code ganker大神博客 http://codeganker.blogspot.com/2014/03/max-points-on-line-leetcode.html
自己写的时候还是有小错误出现,
注意 max 和 local max的初始值均为1, 因为输入为null或空均已判断, 确实最小也是1.。。
还有不要忘记计算斜率的时候加(double)转换
时间复杂度是O(n^2)

空间复杂度是O(n)
/** * 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) {        if(points == null || points.length == 0)            return 0;        // int max = 0;        int max = 1;        for(int i = 0; i < points.length - 1; i++){            Map<Double, Integer> map = new HashMap<>();            int samePointNum = 0;            double ratio = 0.0;            int localMax = 1;                        for(int j = i + 1; j < points.length; j++){                if((points[j].y == points[i].y) && (points[j].x == points[i].x)){                    samePointNum++;                    continue;                }else if(points[j].x == points[i].x){                    ratio = (double)Integer.MAX_VALUE;                }else if(points[j].y == points[i].y){                    ratio = 0.0;                }else{                    ratio = (double)(points[j].y - points[i].y) / (points[j].x - points[i].x);                }                                if(!map.containsKey(ratio)){                    map.put(ratio, 2);                }else{                    map.put(ratio, map.get(ratio) + 1);                }            }            for(Integer num : map.values()){                localMax = Math.max(num, localMax);            }            localMax += samePointNum;            max = Math.max(localMax, max);        }                return max;    }}


0 0
原创粉丝点击