• leetcode 149. Max Points on a Line --------- java


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

     求二维平面上n个点中,最多共线的点数。
     
     
    1、比较直观的方法是,三层循环,以任意两点划线,判断第三个点是否在这条直线上。
     
    比较暴力
     
    2、使用map来记录每个点的最大数目。
     
    /**
     * 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.length < 3) return points.length;
            
            int max = 0;//用于返回的结果,即共线点的最大个数
            Map<Double, Integer> map = new HashMap<Double, Integer>();//保存同一个斜率的点的个数
            
            for (int i = 0; i < points.length; i++) {//以每一个点为固定点
                map.clear();
                int duplicate = 1;//记录跟固定点重合的个数
                
                for(int j = i+1 ; j < points.length; j++){//遍历其他点,求其与固定点之间的斜率
                    double slope = 0.0;//斜率
                    
                    if (points[i].x == points[j].x && points[i].y == points[j].y) {//如果跟固定点重合
                        duplicate++;
                        continue;
                    } else if (points[i].x == points[j].x) {//如果跟固定点在同一条竖线上,斜率设为最大值
                        slope = Integer.MAX_VALUE;
                    } else if( points[i].y == points[j].y ){//计算该点与固定点的斜率
                        slope = 0;
                    } else{
                        slope = 1.0 * (points[i].y - points[j].y) / (points[i].x - points[j].x);
                    }
                    map.put(slope, map.containsKey(slope) ? map.get(slope) + 1 : 1);
                }
                
                //更新最优解
                if (map.keySet().size() == 0) {//如果map为空
                    max = duplicate > max ? duplicate : max;
                } else {
                    for (double key : map.keySet()) {
                        max = Math.max((duplicate + map.get(key)), max); 
                    }
                }
            }
            return max;
        }
    }
  • 相关阅读:
    JavaScript DOM 编程艺术 公用方法
    JavaScript DOM 编程艺术
    Echart 的formatter及重写line chart
    PHP 导出csv
    Linux 搭建PHP环境
    学习新思路
    fork产生子进程利用pipe管道通信
    进程间通信 管道
    进程间通信(IPC) 简介
    java 多态
  • 原文地址:https://www.cnblogs.com/xiaoba1203/p/6078350.html
Copyright © 2020-2023  润新知