LintCode:最多有多少个点在一条直线上
来源:互联网 发布:dirt rally for mac 编辑:程序博客网 时间:2024/05/01 23:34
给出二维平面上的n个点,求最多有多少点在同一条直线上。
您在真实的面试中是否遇到过这个题?Yes
样例
给出4个点:(1, 2)
, (3, 6)
, (0, 0)
, (1, 3)
。
一条直线上的点最多有3个。
标签 Expand
解题思路:
O(n^2)的时间复杂度,利用2点求斜率,map保存斜率。
需要注意的是2点元素相等和斜率不存在的情况
/*** 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) { // Write your code here if (points == null || points.length == 0) return 0; HashMap<Double, Integer> map = new HashMap<>(); int res = 1; for (int i = 0; i < points.length; i++) { map.clear(); int dup = 0; map.put((double)Integer.MIN_VALUE, 1); for (int j = i+1; j < points.length; j++) { if (points[j].x == points[i].x&&points[j].y == points[i].y) { dup++;continue; } double k; if (points[j].x - points[i].x == 0) { k = Integer.MAX_VALUE; } else { k = 0.0 + (double)(points[j].y - points[i].y) / (double)(points[j].x - points[i].x); } if (map.containsKey(k)) { map.put(k, map.get(k) + 1); } else { map.put(k, 2); } } for (int item : map.values()) { if (item+dup > res) { res = item+dup; } } } return res; }}
0 0
- 【LintCode】最多有多少个点在一条直线上
- LintCode:最多有多少个点在一条直线上
- lintcode,最多有多少个点在一条直线上
- LintCode 最多有多少个点在一条直线上
- 最多有多少个点在一条直线上-LintCode
- lintcode最多有多少个点在一条直线上
- lintcode(186)最多有多少个点在一条直线上
- [LintCode 186] 最多有多少个点在一条直线上(Python)
- LinkCode-最多有多少个点在一条直线上
- 最多有多少个点在一条直线上
- Lint_Code_最多有多少个点在一条直线上
- 最多有多少个点在一条直线上
- 解题报告:最多有多少个点在一条直线上
- 最多有多少个点在同一条直线上
- lintcode-有多少个点在同一条直线上-186
- 186.Max Points on a Line-最多有多少个点在一条直线上(中等题)
- 网易互娱笔试题----最多有多少点在一条直线上
- 二维平面上最多有多少个点在同一条直线上
- NFS技术实现图片共享存储
- nginx 配置代理和虚拟目录示例
- [C++] 老鼠走迷宫(使用递回)
- Android学习之在Eclipse看源代码的技巧
- AJAX中数据格式的转换和分类
- LintCode:最多有多少个点在一条直线上
- iOS ViewController之间传值方法五(使用block)
- maven手动添加本地jar包到本地仓库中
- 一个空类占多少空间?多重继承的空类呢
- l
- 黑马程序员—java开发前奏—java语言概述
- LintCode:最大子数组 II
- 杭电ACM初学者入门 1720
- hdu2512 Bell数