leetcode #149 in cpp
来源:互联网 发布:日本千叶大学知乎 编辑:程序博客网 时间:2024/06/15 05:15
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
Solution:
three points,p1,p2,p3, are on the same line if and only if slope(p2) == slope(p3) where slope of pi is defined as (pi.y - p1.y)/ (pi.x - p1.x).
Think about it in the other way. If p2 has the same slope as p3 does with respect to p, then p, p3, p2 would be on the same line.
algorithm:
for each point p
create a map collecting slope with respect to p
for other point pi
calculate the slope(pi) with respect to p;
increase map[slope(pi)] ( map[slope(pi)] represents the total number of points with slope(pi) with respect to p )
find the max number in the map.
Code:
/** * 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 maxPoint = 0; int x; int y; float slope; map<float,int> slopes; for(int i = 0; i < points.size(); i ++){ slopes.clear(); //collect slopes of point i+1...n with respect to points[i] x = points[i].x; y = points[i].y; int temp_max = 1; for(int j = i + 1; j < points.size(); j ++){ if(points[j].x == x && points[j].y == y){//if the same point temp_max++; continue; } //if not the same point, calculate slope and add 1 to the corresponding entry slope = points[j].x - x == 0 ?INT_MAX:float(points[j].y - y )/(points[j].x -x); if(slopes.find(slope) == slopes.end()){ slopes[slope] = 1; }else{ slopes[slope] ++; } } maxPoint = max(maxPoint, temp_max); //compare num of points[i] in the input first. //this is because if the input contains only points[i] // we wont go into the loop to find the max point for(auto it = slopes.begin(); it!=slopes.end(); ++it){ maxPoint = max(maxPoint, it->second + temp_max ); } } return maxPoint; } };
0 0
- leetcode #149 in cpp
- leetcode #12 in cpp
- Leetcode #13 in cpp
- Leetcode #14 in cpp
- leetcode %15 in cpp
- leetcode #16 in cpp
- leetcode #17 in cpp
- leetcode #18 in cpp
- leetcode #20 in cpp
- leetcode #21 in cpp
- leetcode #22 in cpp
- leetcode #23 in cpp
- leetcode #24 in cpp
- leetcode #25 in cpp
- leetcode #26 in cpp
- leetcode #27 in cpp
- leetcode #28 in cpp
- leetcode #29 in cpp
- PHP函数篇之掌握ord()与chr()函数应用
- mysql中各种连接查询图解
- 1030. Travel Plan (30)
- SHA加密算法Java实现
- 2040亲和数
- leetcode #149 in cpp
- linux内核SPI总线驱动分析(一)
- 一起学习 Swing (1)
- iOS开发 Method Swizzling 方法替换
- missing ios distribution signing for
- python: cannot open shared object file: No such file
- 网马初学
- 沉浸式状态栏
- 在Linux环境下mysql的root密码忘记解决方法,修改root密码