7.6--找过点最多的直线(CC150)

直接两个点确定一条直线。然后两两组合,再写一个看过多少个点的函数。一直更新max就行。


import java.util.Arrays;

public class Solution {

    public static void main(String[] args){
        Point[] a = {new Point(0,0),new Point(1,1),new Point(2,2),new Point(0,3)};

        System.out.println(Arrays.toString(getLine(a,4)));
    }
    public static  double[] getLine(Point[] p, int n){
        double[] resLast = new double[2];
        //思路:两个点得到一条直线。
        int max = 0;
        for(int i = 0; i < p.length; i++){
            for(int j = i + 1; j < p.length; j++){
                double[] res = new double[2];
                //把直线求出来。并算出个数
                int num = 0;
                res[0] = (p[j].y - p[i].y) * 1.0 / (p[j].x - p[i].x);
                res[1] = p[j].y - res[0] *p[j].x;
                num = num(p,res    );
                if(num > max){
                    max = num;
                    resLast = res;
                }
            }
        }

        return resLast;
    }

    public static int num(Point[] p, double[] res){
        int num = 0;
        for(int i = 0; i < p.length; i++){
            if(p[i].y == (p[i].x * res[0] + res[1])){
                num++;
            }
        }

        return num;
    }


}

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;
    }
}


 
原文地址:https://www.cnblogs.com/yueyebigdata/p/5090072.html