LintCode:最多有多少个点在一条直线上

给出二维平面上的n个点,求最多有多少点在同一条直线上。

您在真实的面试中是否遇到过这个题?  
Yes
样例

给出4个点:(1, 2)(3, 6)(0, 0)(1, 3)

一条直线上的点最多有3个。

标签   Expand  
解题思路:
O(n^2)的时间复杂度,利用2点求斜率,map保存斜率。
需要注意的是2点元素相等和斜率不存在的情况

/**
* Definition for a point.
* class Point {
*     int x;
*     int y;
*     Point() { x = 0; y = 0; }
*     Point(int a, int b) { x = a; y = b; }
* }
*/
public class Solution {
    /**
     * @param points an array of point
     * @return an integer
     */
    public int maxPoints(Point[] points) {
        // Write your code here
          if (points == null || points.length == 0)
               return 0;
          HashMap map = new HashMap<>();
          int res = 1;
          for (int i = 0; i < points.length; i++) {
              map.clear();
               int dup = 0;          
               map.put((double)Integer.MIN_VALUE, 1);
               for (int j = i+1; j < points.length; j++) {
                    if (points[j].x == points[i].x&&points[j].y == points[i].y) {
                         dup++;continue;
                    }
                    double k;
                    if (points[j].x - points[i].x == 0) {
                         k = Integer.MAX_VALUE;
                    } else {
                         k = 0.0 + (double)(points[j].y - points[i].y)
                                   / (double)(points[j].x - points[i].x);
                    }
                    if (map.containsKey(k)) {
                         map.put(k, map.get(k) + 1);
                    } else {
                         map.put(k, 2);
                    }
               }
               for (int item : map.values()) {
                    if (item+dup > res) {
                         res = item+dup;
                    }
               }
          }
          return res;
    }
}



你可能感兴趣的:(LintCode:最多有多少个点在一条直线上)