注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号
x
(另外一种方法是把所有直线用A, B 两个参数来表示, 然后遍历所有直线,用HashMap计数)
我采用的是“定出发点,找斜率相同直线”的方法,思路类似。- /**
- * 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 {
- public int maxPoints(Point[] points) {
- if (points == null) {
- return 0;
- }
- int maxPoints = 0;
- int n = points.length;
- // store the number of points on a particular
- HashMap<Double, Integer> map;
- for (int i = 0; i < n; ++i) {
- map = new HashMap<>();
- int samePoints = 0;
- int maxSameLines = 0;
- for (int j = i + 1; j < n; ++j) {
- if (points[i].x == points[j].x && points[i].y == points[j].y) {
- samePoints++;
- continue;
- }
- double gradient = 0.0;
- if (points[i].y != points[j].y)
- gradient = points[i].x == points[j].x ? Double.MAX_VALUE : (double)(points[j].y - points[i].y) / (double)(points[j].x - points[i].x);
- //use and update the map;
- if (map.containsKey(gradient)) {
- map.put(gradient, map.get(gradient) + 1);
- } else {
- map.put(gradient, 1);
- }
- maxSameLines = Math.max(maxSameLines, map.get(gradient));
- }
- maxPoints = Math.max(maxPoints, maxSameLines + samePoints + 1);
- }
- return maxPoints;
- }
- }
复制代码 |