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.

     1 import java.util.HashMap;
     2 import java.util.Iterator;
     3 
     4 public class Solution {
     5     public int maxPoints(Point[] points) {
     6         int maxNums = 0;
     7         HashMap<Float, Integer> kAndLineNum = new HashMap<Float, Integer>();
     8         kAndLineNum.put(Float.MAX_VALUE, 0);
     9         int duplicate = 1;
    10         
    11         for(int i = 0; i < points.length; i++){
    12             kAndLineNum.clear();
    13             duplicate = 1;
    14             kAndLineNum.put(Float.MAX_VALUE, 0);
    15             
    16             for(int j = 0; j < points.length; j++){
    17                 if(i == j)                        //
    18                     continue;
    19                 if(points[i].x == points[j].x && points[i].y == points[j].y){                //重复点
    20                     duplicate ++;
    21                     continue;
    22                 }
    23                 float k = 0;
    24                 k = points[i].x == points[j].x ? Float.MAX_VALUE : (float)(points[i].y - points[j].y) / (points[i].x - points[j].x);    //计算斜率
    25                 if(kAndLineNum.get(k) != null){                                                //和其他点在同一直线上
    26                     Integer tempLineNum = kAndLineNum.get(k);
    27                     tempLineNum ++;
    28                     kAndLineNum.put(k, tempLineNum);
    29                 }//if
    30                 else{                                                                        //和其他点不在同意直线上
    31                     kAndLineNum.put(k, 1);
    32                 }//else
    33             }//for
    34             
    35             for(Iterator<Float> iterator = kAndLineNum.keySet().iterator(); iterator.hasNext();){
    36                 Float kValue = iterator.next();
    37                 int pointsNum = kAndLineNum.get(kValue);
    38                 maxNums = maxNums > (pointsNum + duplicate) ? maxNums : (pointsNum + duplicate);
    39             }//for
    40         }//for
    41         
    42         return maxNums;
    43     }
    44 }
  • 相关阅读:
    C++程序设计入门--前言
    C++ string_view 的坑
    从OGRE,GAMEPLAY3D,COCOS2D-X看开源
    抽烟解闷的程序员
    一个团队应该是什么样
    准备开始接手公司的项目
    两位印象深刻的同事
    一段故事结束,一段生活开始
    starling性能优化总结(毫无疑问还是转载)
    知道端口号如何查看应用位置
  • 原文地址:https://www.cnblogs.com/luckygxf/p/4263119.html
Copyright © 2011-2022 走看看