• 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.

    思路: 从 points[] 中依次取出一个点,然后依次和后面一个点组成一条直线。 y = ax+b;

    然后再遍历所有的点看是否满足当前的斜率a 和 截距 b。 如果满足count++。维护一个max, 每次遍历完将count和max比较取最大.

    /**
     * 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 len = points.length;
            int max = 1;
            for(int i = 0; i < len; i++){
                Point point1 = points[i];
                for(int j = i+1; j<len; j++){
                    Point point2 = points[j];
                    int count = 0;
                    
                    if(point1.x == point2.x){
                        for(int z = 0; z < len; z++){
                            if(points[z].x == point1.x)
                                count++;
                        }
                    }else{
                           double x1 = point1.x;
                            double y1 = point1.y;
                            double x2 = point2.x;
                            double y2 = point2.y;
                            double a = (y1 - y2) / (x1 - x2);
                            // 这里的b 是根据 y1 = ax1+b 和 y2 = ax2+b 求出来的
                            double b = (y1 * x2 - y2 * x1) / (x2 - x1);
    
                        for(int z = 0; z < len; z++){
                            if(Math.abs(points[z].x * a + b - points[z].y) < 0.000001)
                                count++;
                        }
                    }
    
                    if(count > max)
                        max = count;
                }
            }
            return max;
        }
    }
  • 相关阅读:
    关于 Uboot 中有趣的 0xdeadbeef 填充
    举例分析 Makefile 中的 filter 与 filter-out 函数
    java时间"yyyy-mm-dd HH:mm:ss"转成Date
    mysql 5.8 查询最新一条数据
    mybatis 打印SQL
    mybatis动态sql中的trim标签的使用
    Mybatis 动态 SQL
    Linux mysql启动与关闭
    maven 添加自己下载的jar包到本地仓库
    centos 安装java1.8
  • 原文地址:https://www.cnblogs.com/RazerLu/p/3557094.html
Copyright © 2020-2023  润新知