欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

求最多能有多少个点位于同一直线上

程序员文章站 2022-04-01 18:41:58
...
题目描述
对于给定的n个位于同一二维平面上的点,求最多能有多少个点位于同一直线上
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
/**
 * Definition for a point.
 * class Point {
 *     int x;
 *     int y;
 *     Point() { x = 0; y = 0; }
 *     Point(int a, int b) { x = a; y = b; }
 * }
 */
import java.util.*;
 
public class Solution {
    public int maxPoints(Point[] points) {
        int len = points.length;
        if(len < 2)
            return len;
        int max_points = 0;
        for(int i = 0; i < len; i++){
            int dup = 0, vlt = 0;  //重合个数,垂直个数
            Point a = points[i];
            Map<Float,Integer> map = new HashMap<>();   //key为斜率
            for(int j = 0; j < len; j++){
                if(i == j) continue;
                else{
                    Point b = points[j];
                    if(a.x == b.x){
                        if(a.y == b.y) dup++;
                        else vlt++;
                    }
                    else{
                        float k = (float)(b.y - a.y)/(b.x - a.x);
                        if(map.get(k) == null) map.put(k, 1);
                        else map.put(k, 1 + map.get(k));
                    }
                }
            }
            int max = vlt;
            for(float k :map.keySet()){
                max = Math.max(max, map.get(k));
            }
            max_points = Math.max(max_points, max + dup);   //加上重复点的个数
        }
        return max_points + 1;
    }
}

相关标签: 牛客网-leetcode