leetcode149
/*
* A line is determined by two factors,say y=ax+b
*
* If two points(x1,y1) (x2,y2) are on the same line(Of course). * Consider the gap between two points. * We have (y2-y1)=a(x2-x1),a=(y2-y1)/(x2-x1) a is a rational, b is canceled since b is a constant * If a third point (x3,y3) are on the same line. So we must have y3=ax3+b * Thus,(y3-y1)/(x3-x1)=(y2-y1)/(x2-x1)=a * Since a is a rational, there exists y0 and x0, y0/x0=(y3-y1)/(x3-x1)=(y2-y1)/(x2-x1)=a * So we can use y0&x0 to track a line;
*/ public class Solution{
public int maxPoints(Point[] points) {
if (points==null) return 0;
if (points.length<=2) return points.length; Map<Integer,Map<Integer,Integer>> map = new HashMap<Integer,Map<Integer,Integer>>();
int result=0;
for (int i=0;i<points.length;i++){
map.clear();
int overlap=0,max=0;
for (int j=i+1;j<points.length;j++){
int x=points[j].x-points[i].x;
int y=points[j].y-points[i].y;
if (x==0&&y==0){
overlap++;
continue;
}
int gcd=generateGCD(x,y);
if (gcd!=0){
x/=gcd;
y/=gcd;
} if (map.containsKey(x)){
if (map.get(x).containsKey(y)){
map.get(x).put(y, map.get(x).get(y)+1);
}else{
map.get(x).put(y, 1);
}
}else{
Map<Integer,Integer> m = new HashMap<Integer,Integer>();
m.put(y, 1);
map.put(x, m);
}
max=Math.max(max, map.get(x).get(y));
}
result=Math.max(result, max+overlap+1);
}
return result; }
private int generateGCD(int a,int b){ if (b==0) return a;
else return generateGCD(b,a%b); }
}
参考:https://leetcode.com/problems/max-points-on-a-line/discuss/47113/A-java-solution-with-notes
leetcode149的更多相关文章
- [Swift]LeetCode149. 直线上最多的点数 | Max Points on a Line
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line. ...
- LeetCode149:Max Points on a Line
题目: Given n points on a 2D plane, find the maximum number of points that lie on the same straight li ...
随机推荐
- IDEA创建一个Mybatis逆向工程
Mybatis逆向工程简介: MyBatis Generator (MBG) 是一个Mybatis的代码生成器 MyBatis 和 iBATIS. 他可以生成Mybatis各个版本的代码,和iBATI ...
- Quartz不用配置文件配置启动
StdSchedulerFactory schedulerFactory = null; try { schedulerFactory = new StdSchedulerFactory(); Pro ...
- python学习疑问
1.(已解决) test = [1, 2, 3, 4] ", id(test)) def func(a): ", id(a)) a = a.remove(1) ", id ...
- PAT 甲级 1006 Sign In and Sign Out (25)(25 分)
1006 Sign In and Sign Out (25)(25 分) At the beginning of every day, the first person who signs in th ...
- php的方法
字符串: strlen(): 字符串的个数: . : 通过.来进行字符串的拼接: 数组: count(): 数组的 个数: is_array(): 判断是不是一个数组: 实参的方法: func_num ...
- Underscore.js(1.9.1) 封装库
// Underscore.js 1.9.1// http://underscorejs.org// (c) 2009-2018 Jeremy Ashkenas, DocumentCloud and ...
- [UE4]widget事件:On Mouse Enter、On Move Leave、Set Color And Opactiy
只要是widget对象,都具有On Mouse Enter.On Move Leave事件
- [UE4]控件模板参数
创建的时候就会变成这样了.
- U3d学习001-RollBox例子
1.世界坐标系和局部坐标系(参照物坐标系)——以参照物为父物体节点 2.刚体组件: 获得GetComponent<Rigidbody>(); 移动AddForce(n ...
- python数据类型总结
按存值个数区分 标量/原子类型 数字,字符串 容器类型 列表,元组,字典 按可变不可变区分 可变 列表,字典 不可变 数字,字符串,元组 按访问顺序区分 直接访问 数字 顺序访问(序列类型) 字符串, ...