1. 程式人生 > >lintcode,最多有多少個點在一條直線上

lintcode,最多有多少個點在一條直線上

給出二維平面上的n個點,求最多有多少點在同一條直線上。
樣例
給出4個點:(1, 2), (3, 6), (0, 0), (1, 3)。
一條直線上的點最多有3個。

解題思路:從第一個點開始遍歷,每次和其他所有點對比,判斷是否是重合點,以及是否是同一x值的點,map用來儲存斜率,然後判斷斜率是否存在,每次更新max。
一刷沒ac

/**
 * 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) { if(points == null || points.length == 0) return 0; if(points.length <= 2) return points.length; int result = 0; for(int i = 0
; i < points.length; i++){ int pointx = points[i].x; int pointy = points[i].y; HashMap<Double, Integer> map = new HashMap<Double, Integer>(); int samep = 0; int samex = 1; for(int j = 0; j < points.length; j++){ if
(j != i){ if(points[j].x == points[i].x && points[j].y == points[i].y) samep++; if(points[j].x == points[i].x){ samex++; continue; } double k = (double)(points[j].y - points[i].y) / (points[j].x - points[i].x); if(map.containsKey(k)) map.put(k,map.get(k)+1); else map.put(k,2); result = Math.max(result, map.get(k)+samep); } } result = Math.max(result, samex); } return result; } }