LeetCode—Max Points on a Line
来源:互联网 发布:qq源码多少行 编辑:程序博客网 时间:2024/05/20 18:20
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
分析:
任意一条直线都可以表述为
y = ax + b
假设,有两个点(x1,y1), (x2,y2),如果他们都在这条直线上则有
y1 = kx1 +b
y2 = kx2 +b
由此可以得到关系,k = (y2-y1)/(x2-x1)。即如果点c和点a的斜率为k, 而点b和点a的斜率也为k,可以知道点c和点b也在一条线上。
这里同时有几个地方需要注意:
1: 如果只有一个点的处理方式
2:如果遇到两个点的连线是平行的,那么这个斜率应该怎么整理
/** * 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) { map<float , int> mp; float k; int max = 0; int repeatNum = 0; if(points.size() == 0) { return 0; } if(points.size() == 1) { return 1; } for(int i = 0; i < points.size(); i++) { mp.clear(); mp[INT_MIN] = 0; repeatNum = 1; //<the point his own is 1 for(int j = 0; j < points.size(); j++) { if(i == j) continue; if((points[i].x == points[j].x)&&(points[i].y == points[j].y)) { repeatNum++; continue; } if(points[i].x == points[j].x) { k = INT_MAX; mp[k]++; } else { k = (float)(points[i].y-points[j].y)/(points[i].x-points[j].x);//<这里必须加上float类型转换,要不可能出来的k值都是0 mp[k]++; } } map<float, int>::iterator it = mp.begin(); for(; it != mp.end(); it++) //must use the !=, can not use the < { if((it->second+repeatNum) > max) { max = it->second+repeatNum; } } } return max; }};
这里面实现的时候有几个比较重要的点需要关注:
1 repeatNum
需要记录同样点的数量
2、mp[INT_MIN] = 0;
保证poins中只有一个结点,还有points中只有重复元素时,mp中没有元素。这两种极端情况。
3 在做除法获得斜率的过程当中
需要转换为float类型
0 0
- LeetCode—Max Points on a Line
- Max Points on a Line | leetcode
- Max Points on a Line LEETCODE
- 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
- Leetcode: Max Points on a Line
- LeetCode OJ:Max Points on a Line
- Leetcode Max Points on a Line
- Leetcode: Max Points on a Line .
- [Leetcode] Max Points on a Line (Java)
- leetcode:【Max Points on a Line】
- Max Points on a Line - LeetCode
- LeetCode:Max Points on a Line
- [LeetCode] Max Points on a Line
- leetcode - Max Points on a Line
- Ubuntu 14.04中文输入法的安装
- Java IO流分析整理
- 数据库作业开发二
- Android adb logcat的使用
- Oracle数据闪回
- LeetCode—Max Points on a Line
- 5 Lightweight Alternatives to Apache and IIS Web Servers
- iOS:编译错误Unknown type name ‘***'
- H电-Problem Archive-1879-继续畅通工程
- 素数
- 翼支付门户架构之Spring Security框架介绍
- Undefined function 'conv2' for input arguments of type 'double' and attributes 'full 3d complex'.
- Java IO流学习总结
- java的内存泄露是如何发生的,如何避免和发现?