Max Points on a Line
2014-01-09 15:08
357 查看
Given n points
on a 2D plane, find the maximum number of points that lie on the same straight line.
1. 重复点要考虑,做之前问问考官有没有重复点;
2. java 中double 有0.0 和-0.0之分,所以要多加一个判断。。。
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.text.DecimalFormat; public class Solution { public int maxPoints(Point[] points) { Map<Double, Integer> slopeMap = new HashMap<>(); int max = 0; int n = points.length; if (n == 0) { return 0; } if (n == 1) { return 1; } for (int i = 0; i < n; i++) { int duplicate = 1; Point p1 = points[i]; slopeMap.clear(); slopeMap.put(Double.MIN_VALUE, 0); for (int j = i + 1; j < n; j++) { Point p2 = points[j]; double slope = 0.0; if (p2.x - p1.x != 0) { slope = (p2.y - p1.y) * 1.00 / (p2.x - p1.x); } else if (p2.y == p1.y) { duplicate++; continue; } else { slope = Double.MAX_VALUE; } if (slope == -0.0) { slope = 0.0; } if (slopeMap.containsKey(slope)) { int value = slopeMap.get(slope); slopeMap.put(slope, value + 1); } else{ slopeMap.put(slope, 1); } } for (double key : slopeMap.keySet()) { int value = slopeMap.get(key); if (value + duplicate > max) { max = value + duplicate; } } } return max; } }这道题值得注意的地方有很多:
1. 重复点要考虑,做之前问问考官有没有重复点;
2. java 中double 有0.0 和-0.0之分,所以要多加一个判断。。。
相关文章推荐
- Max Points on a Line 同一直线上的点
- Leetcode: Max Points on a Line
- 【LeetCode with Python】 Max Points on a Line
- LeetCode:149_Max Points on a line | 寻找一条直线上最多点的数量 | Hard
- LeetCode || Max Points on a Line
- Max Points on a Line
- 【leetcode】Max Points on a Line
- 【LeetCode】max-points-on-a-line一条线上最多点
- Leetcode_max-points-on-a-line(c++ and python version)
- leetcode_Max Points on a Line
- Max Points on a Line -- leetcode
- Max Points on a Line(leetcode)
- Max Points on a Line
- Problem Max Points On a Line
- Max Points on a Line
- leetcode3题解 Max Points on a line
- Max Points on a Line leetcode java
- [leetcode-149]Max Points on a Line(java)
- LeetCode Max Points on a Line
- LeetCode:max-points-on-a-line