博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LintCode] Max Points on a Line 共线点个数
阅读量:6822 次
发布时间:2019-06-26

本文共 3024 字,大约阅读时间需要 10 分钟。

 

Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.

 
Example

Given 4 points: (1,2), (3,6), (0,0), (1,3).

The maximum number is 3.

 

LeetCode上的原题,请参见我之前的博客。

 

解法一:

class Solution {public:    /**     * @param points an array of point     * @return an integer     */    int maxPoints(vector
& points) { int res = 0, n = points.size(); for (int i = 0; i < n; ++i) { int duplicate = 1; unordered_map
m; for (int j = i + 1; j < n; ++j) { if (points[i].x == points[j].x && points[i].y == points[j].y) { ++duplicate; } else if (points[i].x == points[j].x) { ++m[INT_MAX]; } else { double slope = (double)(points[j].y - points[i].y) / (points[j].x - points[i].x); ++m[slope]; } } res = max(res, duplicate); for (auto it : m) { res = max(res, it.second + duplicate); } } return res; }};

 

解法二:

class Solution {public:    /**     * @param points an array of point     * @return an integer     */    int maxPoints(vector
& points) { int res = 0, n = points.size(); for (int i = 0; i < n; ++i) { int duplicate = 1; map
, int> m; for (int j = i + 1; j < n; ++j) { if (points[i].x == points[j].x && points[i].y == points[j].y) { ++duplicate; continue; } int dx = points[j].x - points[i].x; int dy = points[j].y - points[i].y; int d = gcd(dx, dy); ++m[{dx / d, dy / d}]; } res = max(res, duplicate); for (auto it : m) { res = max(res, it.second + duplicate); } } return res; } int gcd(int a, int b) { return (b == 0) ? a : gcd(b, a % b); }};

 

解法三:

class Solution {public:    /**     * @param points an array of point     * @return an integer     */    int maxPoints(vector
& points) { int res = 1; for (int i = 0; i < points.size(); ++i) { int repeat = 1; for (int j = i + 1; j < points.size(); ++j) { int cnt = 0; int x1 = points[i].x, y1 = points[i].y; int x2 = points[j].x, y2 = points[j].y; if (x1 == x2 && y1 == y2) {++repeat; continue;} for (int k = 0; k < points.size(); ++k) { int x3 = points[k].x, y3 = points[k].y; if (x1 * y2 + x2 * y3 + x3 * y1 - x3 * y2 - x2 * y1 - x1 * y3 == 0) { ++cnt; } } res = max(res, cnt); } res = max(res, repeat); } return points.empty() ? 0 : res; }};

 

转载地址:http://afozl.baihongyu.com/

你可能感兴趣的文章
try-catch中导致全局变量无法变化的bug
查看>>
Js中数组的操作
查看>>
浏览器缓存 from memory cache与from disk cache详解
查看>>
php编译常用选项
查看>>
Docker Machine 简介
查看>>
Angular4错误提示的说明(一)
查看>>
CCNA+NP学习笔记—交换网络篇
查看>>
一张图说明Linux启动过程
查看>>
Provider处理请求逻辑梳理
查看>>
我的友情链接
查看>>
查看当前服务链接数
查看>>
Open-Falcon 互联网企业级监控系统解决方案(2)
查看>>
抄录一份linux哲学思想
查看>>
DBLIKE创建命令
查看>>
cesiumjs开发实践(五) 坐标变换
查看>>
明明白白学C#第0章准备工作
查看>>
Xamarin.Forms单元控件Cell
查看>>
Linux下MySQL备份以及crontab定时备份
查看>>
Exchange 2016和 O365 混合部署系列三之混合配置
查看>>
shell脚本生成服务演示服务启动、停止过程。
查看>>