[LeetCode]Max Points on a Line
2015-06-11 19:58
393 查看
Given n points
on a 2D plane, find the maximum number of points that lie on the same straight line.
[LeetCode Source]
思路:对每一个节点求和其他节点的斜率,用hash_map统计斜率相同的点数。时间O(N^2),空间O(N)。应该有更简单可以在O(1)空间的算法,暂时没想出来。
这道题目AC率低的原因是由于各种边界条件,要注意:
1)有重复点的情况;
2)点数少于2的情况;
3)有垂直点(斜率为无穷)的情况。
遍历节点时注意已经遍历的节点不用再遍历了,避免重复遍历。
比如已经对前i个节点求了最大值,对第i+1个节点就不用再遍历前i个节点算斜率,因为之前节点已经对i+1点求过斜率算过最大值。
代码如下:
on a 2D plane, find the maximum number of points that lie on the same straight line.
[LeetCode Source]
思路:对每一个节点求和其他节点的斜率,用hash_map统计斜率相同的点数。时间O(N^2),空间O(N)。应该有更简单可以在O(1)空间的算法,暂时没想出来。
这道题目AC率低的原因是由于各种边界条件,要注意:
1)有重复点的情况;
2)点数少于2的情况;
3)有垂直点(斜率为无穷)的情况。
遍历节点时注意已经遍历的节点不用再遍历了,避免重复遍历。
比如已经对前i个节点求了最大值,对第i+1个节点就不用再遍历前i个节点算斜率,因为之前节点已经对i+1点求过斜率算过最大值。
代码如下:
/** * Definition for a point. * struct Point { * int x; * int y; * Point() : x(0), y(0) {} * Point(int a, int b) : x(a), y(b) {} * }; */ class Solution { public: int maxPoints(vector<Point>& points) { int size = points.size(); if(size<=1) return size; int res = 0; for(int i=0;i<size;++i){ int local = 1; int Vertical = 0; int Dup = 0; double k= 0.0; unordered_map<double,int> map; for(int j=i+1;j<size;++j){ //只需对i+1大的值的点求线,因为以之前为小于i+1起点的直线已经遍历过i+1点,再求解就是重复遍历了 if(points[i].x == points[j].x){ if(points[i].y == points[j].y) Dup++; //统计重复的点数 else Vertical++; //统计水平的点数 } else{ k = (points[j].y-points[i].y)*1.0/(points[j].x-points[i].x); map[k]==0?map[k]=2:map[k]++; //计算在同一直线上的点 local = max(local,map[k]); //和该节点在同一直线上的最大点数 } } local = max(local+Dup,Vertical+Dup+1);//该节点加上重复的节点,注意水平和重复节点有可能是最大值 res = max(local,res);//计算所有解中的最大的节点 } return res; } };
相关文章推荐
- System.exit()方法的作用
- hdu 3631 Shortest Path(Floyd)
- Hibernate学习笔记之三种查询方式
- x210v3开发板u-boot-2012.10移植之九---运行阵地转移,赶紧把BL2扔到内存
- SQL结构化查询语言及Mysql基本操作
- hdu 3631 Shortest Path(Floyd)
- 设计模式之 - 总结
- 汇编语言学习笔记(5)——[bx]和loop
- Karma和Jasmine自动化单元测试
- remove-nth-node-from-end-of-list
- 探索 OpenStack 之(8):Neutron 深入探索之 OVS + GRE 之 完整网络流程 篇(转)
- Applet 数字签名技术完全攻略
- JavaScript继承详解
- iBokan_ios80_自学系列_1(测试效果)
- UITableView小知识点(二)
- x210v3开发板u-boot-2012.10移植之八---DDR2初始化我也能搞定
- 阿凡达是脸,教你的脸在线(包括URL和使用)
- HttpUrlConnection retryPost 重发
- 32位操作系统和64位操作系统的数据类型大小
- Android开发者的演示工具(真机测试)——asm.jar