zoukankan      html  css  js  c++  java
  • 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;
        }
    }
  • 相关阅读:
    Insert Buffering
    B-Tree vs LSM-tree
    MySQL 5.6 死锁演示 及 日志分析
    MySQL索引
    InnoDB的三个关键特性
    MySQL如何优化GROUP BY :松散索引扫描 VS 紧凑索引扫描
    MySql 自适应哈希索引
    母牛的故事
    简单的java程序
    一些变量的比较
  • 原文地址:https://www.cnblogs.com/RazerLu/p/3557094.html
Copyright © 2011-2022 走看看