leetcode题解-149. 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.
题目是寻找平面中所有点在同一条直线上的最大个数。一种简单的思路就是使用Map来保存每条直线上的点数,然后遍历数组中的每个点即可。代码如下所示:

import java.util.HashMap;
import java.util.Map;

public class maxPoints {

    static class Point {
         int x;
         int y;
         Point() { x = 0; y = 0; }
         Point(int a, int b) { x = a; y = b; }
    }

    public int maxPoints(Point[] points) {
        if(points == null || points.length == 0) return 0;
        int max = 0;
        for(int i=0;i1;i++){
            //对各个点都初始化一个Map来保存该点所确定的所有直线上的点数
            HashMap pointsOnLine = new HashMap<>();
            //这两个变量分别保存相同点个数和x相同点的个数
            int samePoint = 0, localMax = 0;
            //对每个点而言,遍历所有其他点
            for(int j=i+1;jint x = points[j].x - points[i].x;
                int y = points[j].y - points[i].y;
                if(x == 0 && y== 0) {
                    samePoint++;
                    continue;
                }
                //计算两个点确定的直线的斜率。只要斜率相同就说明该店在该直线上
                double ratio = findRatio(x,y);
                if(!pointsOnLine.containsKey(ratio))
                    pointsOnLine.put(ratio, 1);
                //如果该斜率已经存在于map中,那么将其计数加一
                else pointsOnLine.put(ratio, pointsOnLine.get(ratio)+1);
                localMax = Math.max(localMax, pointsOnLine.get(ratio));
            }
            max = Math.max(max, localMax + samePoint);
        }
        return max+1;
    }
    private Double findRatio(int x, int y){
        if(y == 0) return Double.MAX_VALUE;
        else return (double)x/(double) y + 0.0;
    }

    public static void main(String[] args){
        Point p0 = new Point(0, 0);
        Point p1 = new Point(1, 1);
        Point p2 = new Point(1, -1);
        Point [] points = {p0, p1, p2};
    }

}

你可能感兴趣的:(leetcode刷题,leetcode)