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

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

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

  • 解题思路

    若两个点共线,则有如下情况:

    • 两个点重合
    • 两个点的x坐标相同(斜率无穷大)
    • 两个点的斜率相同
      y1 = k * x1 + b;
      y2 = k * x2 + b;
      则有k = (y1 - y2) / (x1 - x2);
  • 实现代码

/*****************************************************************    *  @Author   : 楚兴    *  @Date     : 2015/2/9 20:46    *  @Status   : Accepted    *  @Runtime  : 35 ms******************************************************************/#include 
#include
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
&points) { if (points.size() <= 2) { return points.size(); } int maxNum = 0; unordered_map
mymap; int copy; //重复的点个数 double k; //斜率 for (int i = 0; i < points.size(); i++) { mymap.clear(); copy = 0; //坐标相同点的个数 for (int j = 0; j < points.size(); j++) { if (j == i) { continue; } if (points[i].x == points[j].x && points[i].y == points[j].y) { copy++; //相同点 continue; } if (points[i].x == points[j].x) { mymap[INT_MAX]++; //斜率不存在 } else { k = (double)(points[i].y - points[j].y) / (points[i].x - points[j].x); mymap[k]++; } } if (mymap.size() == 0) { maxNum = maxNum > copy ? maxNum : copy; } int temp; for (auto it = mymap.cbegin(); it != mymap.cend(); it++) { temp = (*it).second + copy; maxNum = maxNum > temp ? maxNum : temp; } } return maxNum + 1; //加上自身 }};int main(){ Solution s; vector
points; Point* p1 = new Point(0, 0); Point* p2 = new Point(0, 0); points.push_back(*p1); points.push_back(*p1); cout<
<

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

你可能感兴趣的文章
JProfiler_SN_8_x.txt
查看>>
IntelliJ IDEA 社区版没有 Spring Initializr
查看>>
android使用proguard混淆生成jar包
查看>>
疯狂Activiti6.0连载(12)DMN规范概述
查看>>
3-Elasticsearch查询API
查看>>
RemotelyAnywhere安装使用指南
查看>>
PHP中利用ICONV转化字符串编码出错【DETECTED AN ILLEGAL CHARAC...
查看>>
display table 标签
查看>>
mysql 日志维护
查看>>
inux多线程顺序控制的示例
查看>>
2. ASIHttpRequest-发送数据
查看>>
[应用模板]移动应用界面
查看>>
嵌入式Linux C编程 02
查看>>
sql server支持连接管理功能
查看>>
java的强制类型转换想到的
查看>>
简要介绍cookie与session的区别与联系
查看>>
mysql flush用法
查看>>
response.setHeader()的用法
查看>>
一位前辈的经验,给正在思考的自己
查看>>
分享一篇关于lucene原理的文章
查看>>