LeetCode Max Points on a Line
2015-11-09 12:37
405 查看
原题链接在这里:https://leetcode.com/problems/max-points-on-a-line/
这道题就是给你一个2D平面,然后给你的数据结构是由横纵坐标表示的点,然后看哪条直线上的点最多。
(1)两点确定一条直线
(2)斜率相同的点落在一条直线上
(3)坐标相同的两个不同的点 算作2个点
利用HashMap,Key值存斜率,Value存此斜率下的点的个数。如果遇到重合的点,same来记录相同点的个数。
维护一个localmax,计算当前情况下的最大值;再维护一个全局Max来计算总的最大值。返回全局Max即可。
Time Complexity is O(n^2). Space is O(n). n是点的个数。
Note: localMax要初始化成1, 最小值就是1, 而不能是0.
一条竖线上的点如[3,4], [3,5]他们的斜率是Infinity. HashMap 的 key 就是infinity.
AC Java:
Reference: /article/4896946.html
这道题就是给你一个2D平面,然后给你的数据结构是由横纵坐标表示的点,然后看哪条直线上的点最多。
(1)两点确定一条直线
(2)斜率相同的点落在一条直线上
(3)坐标相同的两个不同的点 算作2个点
利用HashMap,Key值存斜率,Value存此斜率下的点的个数。如果遇到重合的点,same来记录相同点的个数。
维护一个localmax,计算当前情况下的最大值;再维护一个全局Max来计算总的最大值。返回全局Max即可。
Time Complexity is O(n^2). Space is O(n). n是点的个数。
Note: localMax要初始化成1, 最小值就是1, 而不能是0.
一条竖线上的点如[3,4], [3,5]他们的斜率是Infinity. HashMap 的 key 就是infinity.
AC Java:
/** * Definition for a point. * class Point { * int x; * int y; * Point() { x = 0; y = 0; } * Point(int a, int b) { x = a; y = b; } * } */ public class Solution { public int maxPoints(Point[] points) { if(points == null || points.length == 0){ return 0; } int max = 1; if(points.length == 1){ return max; } for(int i = 0; i<points.length; i++){ HashMap<Float,Integer> hm = new HashMap<Float,Integer>();//key存斜率,value存该斜率上的点 int same = 0; //重合的点的个数 int localMax = 1; //error for(int j = 0; j<points.length; j++){ if(i == j){ continue; }else if(points[i].x == points[j].x && points[i].y == points[j].y){ same++; continue; } float slope = (float)(points[j].y - points[i].y) / (points[j].x - points[i].x); if(!hm.containsKey(slope)){ hm.put(slope,2); }else{ hm.put(slope,hm.get(slope)+1); } } for(int count : hm.values()){ localMax = Math.max(localMax,count); } localMax +=same; max = Math.max(max,localMax); } return max; } }
Reference: /article/4896946.html
相关文章推荐
- 数据库水平切分的实现原理解析——分库,分表,主从,集群,负载均衡器
- IE9浏览器中的My97日历控件刷新后无法打开问题解决办法
- AFN抛出error,过去error里返回的数据。
- FlexSlider插件的详细设置参数
- C++ 中文件流ofstream ifstream
- C语言之文件IO
- 编程之美-求二进制数中1的个数方法整理
- 对于MSP430与SIM900A无法通信的问题解决
- android 源码下载备忘
- 帝国时代II 高清版 steam 4.4 字体替换 微软雅黑
- ThinkPHP3.2.3---更换easyui主题(theme)
- 我的互联网奋斗之路
- android------通用ViewHolder 通用Adapter
- zoj 1601 Count the Colorst(线段树)
- Android编程实现两个Activity之间共享数据及互相访问的方法
- ContentProvider原理及实例
- 伍德里奇计量经济学导论之计算机操作题的R语言实现(多元回归:估计)
- 在request中获取项目路径
- @Controller
- swift UIButton 设置动态图片