穿点最多的直线

这里写图片描述

思路分析:每2个点计算斜率和截距并包装成为一个对象,加入map,统计个数,最后找出最高的。

代码如下:

import java.util.*;

/*
public class Point {
    int x;
    int y;
    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
    public Point() {
        this.x = 0;
        this.y = 0;
    }
}*/
public class DenseLine {
    public double[] getLine(Point[] p, int n) {
               HashMap<Line,Integer> lineNum=new HashMap<Line,Integer>();
       int max=0;
       double slope=Double.POSITIVE_INFINITY,intercept=0;
       //把所有线取出来求出斜率和截距,并用哈希图存储下线条和个数的键值对
       for(int i=0;i<n;i++){
           for(int j=0;j<n;j++){
               double k=(double)(p[j].y-p[i].y)/(p[j].x-p[i].x);
               double b=(double)(p[i].y-k*p[i].x);
               Line line=new Line(k,b);
               if(lineNum.containsKey(line)){
                   int num=lineNum.get(line)+1;
                   lineNum.put(line,num);
                   //不断调整最大值
                   if(num>max){
                       max=num;
                       slope=k;
                       intercept=b;
                   }
               }
               else
                   lineNum.put(line,1);
           }
       }
       return new double[]{slope,intercept};
        // write code here
    }

}
class Line{

        double k;
        double b;

        Line(double k,double b){
            this.k = k;
            this.b = b;
        }

        public boolean isEqualValue(double a,double b){

            return (Math.abs(a-b)<0.00001);
        }

        public boolean equals(Object object){

            if(object instanceof Line)
                {
                if(isEqualValue(k,((Line)object).k)&&isEqualValue(b,((Line)object).b))
                    return true;
                return false;
            }

            return super.equals(object);
        }

        public int hashCode(){
            String str = String.valueOf(k)+String.valueOf(b);
            return str.hashCode();
        }

    }

代码下载:我的github

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值