1. 程式人生 > >leetcode max-points-on-a-line

leetcode max-points-on-a-line

light .get 垂直 題目 keys plan etc highlight subject

題目描述

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

思路:註意垂直和重疊的點

代碼 時間341ms 空間19988k

/**
 * 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 n = points.length;
        if (n <= 2)
            return n;
        
        int res = 0;
        for (int i=0;i<n;i++){
            HashMap<Float, Integer> a = new HashMap<>();
            int vrt = 0;
            int dup = 1;
            int max = 0;
            for (int j=0;j<n;j++){
                if (i==j)
                    continue;
                if (points[i].x == points[j].x){
                    if (points[i].y == points[j].y){
                        dup++;
                    }
                    else {
                        vrt++;
                    }
                }
                else {
                    float grad = (float)(points[j].y-points[i].y)/(points[j].x-points[i].x);
                    if (a.get(grad) == null)
                        a.put(grad, 1);
                    else {
                        a.put(grad, a.get(grad) + 1);
                    }
                }
                
                int tmp = vrt;
                for (float k:a.keySet())
                    tmp = Math.max(tmp, a.get(k));
                
                max = tmp + dup;
            }
            res = Math.max(res, max);
        }
        return res;
    }
}

  

leetcode max-points-on-a-line