[leetCode]:Max Points on a Line
2014-04-23 15:16
441 查看
语言 :JAVA
思路 :1、多点能组成一条直线,则必有基于某起始点,其他点相应的斜率相等。
2、为了避免计算斜率出现的精度问题,采用最大公约数,若a/b = c/d,则必有a/b = e*g/f*g,如此当算出c、d的公约数g后,即可简化右侧等式。所有在一条直线上的 点都会具有相同的e,f值。以e,f为键,值则存储在这条线上的点的数量。
3、注意到例如e,g为(1,-2),(-1,2)是两条不同的线,因此为了加以区别,在gcd()中,保留x轴的数值符号。
代码:
思路 :1、多点能组成一条直线,则必有基于某起始点,其他点相应的斜率相等。
2、为了避免计算斜率出现的精度问题,采用最大公约数,若a/b = c/d,则必有a/b = e*g/f*g,如此当算出c、d的公约数g后,即可简化右侧等式。所有在一条直线上的 点都会具有相同的e,f值。以e,f为键,值则存储在这条线上的点的数量。
3、注意到例如e,g为(1,-2),(-1,2)是两条不同的线,因此为了加以区别,在gcd()中,保留x轴的数值符号。
代码:
/** * 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 { int gcd(int a, int b) { return a==0 ? b : a/Math.abs(a) * Math.abs(gcd(b%a, a)); } public int maxPoints(Point[] points) { int result = 0; for (int i=0; i<points.length; i++) { HashMap<String, Integer> count = new HashMap<String, Integer>(); int same = 1; int mx = 0; int newValue; for (int j=i+1; j<points.length; j++) { int x = points[i].x - points[j].x; int y = points[i].y - points[j].y; int g = gcd(x, y); if (g == 0) { same++; continue; } x /= g; y /= g; String keyString = x + " " + y; if (count.containsKey(keyString)) { newValue = count.get(keyString) + 1; } else { newValue = 1; } count.put(keyString, newValue); mx = Math.max(mx, newValue); } result = Math.max(result, mx+same); } return result; } }
相关文章推荐
- leetcode_149. Max Points on a Line
- Leetcode 149. Max Points on a Line
- Max Points on a Line Leetcode Python
- Leetcode 149-Max Points on a Line
- [Leetcode] 149. Max Points on a Line 解题报告
- 【leetcode】Max Points on a Line
- LeetCode -- Max Points on a Line
- leetcode - Max Points on a Line
- LeetCode:Max Points on a Line
- [LeetCode] Max Points on a Line, Solution
- [LeetCode]149 Max Points on a Line
- LeetCode——Max Points on a Line
- Leetcode: Max Points on a Line .
- LeetCode:Max Points on a Line
- [LeetCode] Max Points on a Line
- LeetCode | 149. Max Points on a Line求多个点里面在一条直线上的点最多有多少个难题
- [LeetCode] max-points-on-a-line
- [LeetCode] Max Points on a Line
- leetcode之Max Points on a Line
- leetcode: Max Points on a Line