Max Points on a Line
2013-12-31 03:14
274 查看
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
算斜率的时候一定注意要格式转换,integer-〉double
算斜率的时候一定注意要格式转换,integer-〉double
/** * 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.util.Hashtable; public class Solution { public int maxPoints(Point[] points) { if(points.length < 1) return 0; int res = 0; Hashtable<Double, Integer> table = new Hashtable<Double, Integer>(); for(int i = 0; i < points.length; i++){ table.clear(); int max = 0; int duplicate = 1; int vertical = 0; for(int j = 0; j < points.length; j++){ if(j == i) continue; if(points[j].x == points[i].x && points[j].y == points[i].y){ duplicate++; continue; } if(points[j].x == points[i].x){ vertical++; continue; } double k = (double)(points[j].y - points[i].y) / (points[j].x - points[i].x); if(!table.containsKey(k)) table.put(k, 1); else table.put(k, table.get(k) + 1); } for(Iterator<Double> it = table.keySet().iterator(); it.hasNext();){ int cur = table.get(it.next()); max = max > cur ? max : cur; } max = max > vertical ? max : vertical; max += duplicate; res = res > max ? res : max; } return res; } }
相关文章推荐
- LeetCode:Max Points on a Line
- Max Points on a Line
- 【LeetCode】149. Max Points on a Line - javascript
- Lintcode186 Max Points on a Line solution 题解
- Max Points on a Line
- max-points-on-a-line
- Max Points on a Line
- Max Points on a Line
- LeetCode149. Max Points on a Line
- leetcodeOJ 149. Max Points on a Line
- 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]149. Max Points on a Line
- leetcode--max-points-on-a-line
- LeetCode: Max Points on a Line 解题报告
- Max Points On a Line--leetcode
- 149.Max Points on a Line
- Max Points on a Line