给你一个数组 points ,其中 points[i] = [xi, yi] 表示 X-Y 平面上的一个点。求最多有多少个点在同一条直线上。
示例 1:
输入:points = [[1,1],[2,2],[3,3]]
输出:3
示例 2:
输入:points = [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]
输出:4
Java
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class maxPoints {
public static int maxPoints(int[][] points){
int n = points.length;
if(n<=2) return n;
int res =2;
for(int i=0;i<n;i++){
Map<String,Integer> has = new HashMap<String,Integer>();
int x1 = points[i][0];
int y1=points[i][1];
for(int j=i+1;j<n;j++){
double a,b,c=0;
int x2 = points[j][0];
int y2=points[j][1];
if(x1==x2){
a = 1;
b = 0;
c = -x1;
if(c ==-0.0) c = c+0.0;
}
else if(y1==y2){
a=0;
b= 1;
c= -y1;
if(c ==-0.0) c = c+0.0;
}
else {
a = 1.0;
b = 1.0 * (x1-x2)/(y2-y1);
c = 1.0 * (x1*y2-x2*y1)/(y1-y2);
if(c ==-0.0) c = c+0.0;
}
String flag = String.valueOf(a)+","+String.valueOf(b)+","+String.valueOf(c);
System.out.println(flag);
if(has.containsKey(flag)){
int num = has.get(flag) + 1;
has.replace(flag, num);
res = Math.max(num,res);
}
else{
has.put(flag, 2);
}
}
}
return res;
}
public static void main(String[] args) {
// int[][] points = {{1,1},{3,2},{5,3},{4,1},{2,3},{1,4}};
int[][] points = {{0,0},{2,2},{-1,-1}};
int res = maxPoints(points);
System.out.println(res);
}
}
Python
def maxPoints( points: List[List[int]])->int:
n = len(points) # 统计点的个数
if(n<=2):
return n
res = 2
for i in range(n):
x1,y1 = points[i][0],points[i][1]
has = {}
for j in range(i+1,n):
x2,y2 = points[j][0],points[j][1]
if x1==x2:
a,b,c = 1,0,-x1
elif y1==y2:
a,b,c = 0,1,-y1
else:
a = 1.0
b = 1.0 * (x1-x2)/(y2-y1)
c = 1.0 * (x1*y2-x2*y1)/(y1-y2)
if (a,b,c) in has.keys():
has[(a,b,c)] +=1
res = max(res,has[(a,b,c)])
else:
has[(a,b,c)] = 2
return res
if __name__=="__main__":
points = [[1, 1], [3, 2], [5, 3], [4, 1], [2, 3], [1, 4]]
res = maxPoints(points)
print(res)