题目链接:https://leetcode.com/problems/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.
Example 1:
Input: [[1,1],[2,2],[3,3]] Output: 3 Explanation: ^ | | o | o | o +-------------> 0 1 2 3 4
Example 2:
Input: [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]] Output: 4 Explanation: ^ | | o | o o | o | o o +-------------------> 0 1 2 3 4 5 6
NOTE: input types have been changed on April 15, 2019. Please reset to default
code definition to get new method signature.
思路:
按照往常的习惯,就会挨个把两个点的斜率求出来,直接根据斜率做个映射表,
但是斜率就有精度问题,因此为了保证精度,可以通过X,Y来表示一条直线的斜率。
同一斜率对应点的数量通过一个Map<Integer, Map<Integer, Integer>> map来表示,
第一个Integer表示X,第二个Integer表示Y,第三个Integer表示该斜率对应的点数。
对每个点,都计算一下该点和其他点连线的斜率,这样对于这个点来说,相同
斜率的直线有多少条,就意味着有多少个点在同一条直线上,因为这些直线是相同的。
另外,如果计算过点A和点B的直线,当算到点B时,就不用再和A连线了,因为AB
这条直线上的点数已经都计算过了。
AC 14ms:
class Solution {
public int maxPoints(int[][] points) {
int n=points.length;
if(n==0)
return 0;
int ans=1;
for(int i=0;i<n;i++){
int samePoints=0;
int max=0;
Map<Integer, Map<Integer, Integer>> map = new HashMap<>();
for(int j=i+1;j<n;j++){
int x=points[i][0]-points[j][0];
int y=points[i][1]-points[j][1];
if(x==0&&y==0){
samePoints++;//解决相同的点。
continue;
}
int g=gcd(x,y);
if(g!=0){
x=x/g;
y=y/g;
}
if(!map.containsKey(x)){
Map<Integer,Integer> m=new HashMap();
m.put(y,1);
map.put(x,m);
}else{
if(map.get(x).containsKey(y))
map.get(x).put(y,map.get(x).get(y)+1);
else
map.get(x).put(y,1);
}
max=Math.max(max,map.get(x).get(y));
}
ans=Math.max(ans,max+samePoints+1);
}
return ans;
}
public int gcd(int a,int b){
return b==0?a:gcd(b,a%b);//辗转相除求最大公约数,4%6=4.所以a和b的大小关系无所谓。
}
}