用公式直接求解
def get_circle(self, p0, p1, r):
if p1[0] == p0[0]:
y0 = y1 = (p0[1]+p1[1]) / 2
deltay = (y0-p0[1]) ** 2
deltax = sqrt(r ** 2 - deltay)
x0 = p1[0] - deltax
x1 = p1[0] + deltax
else:
C1 = (p1[0]**2 + p1[1]**2 - p0[0]**2 - p0[1]**2) / 2 / (p1[0] - p0[0])
C2 = (p1[1] - p0[1]) / (p1[0] - p0[0])
A = 1 + C2**2
B = 2 * (p0[0] - C1) * C2 - 2*p0[1]
C = (p0[0]-C1)**2 + p0[1]**2 - r**2
y0 = (-B + sqrt(B*B - 4 * A * C)) / 2 / A
y1 = (-B - sqrt(B*B - 4 * A * C)) / 2 / A
x0 = C1 - C2 * y0
x1 = C1 - C2 * y1
return [x0, y0], [x1, y1]
leetcode 5415. 圆形靶内的最大飞镖数量
from math import sqrt
class Solution:
def get_dis(self, p0, p1):
return (p0[0]-p1[0])**2 + (p0[1]-p1[1])**2
def get_circle(self, p0, p1, r):
if p1[0] == p0[0]:
y0 = y1 = (p0[1]+p1[1]) / 2
deltay = (y0-p0[1]) ** 2
deltax = sqrt(r ** 2 - deltay)
x0 = p1[0] - deltax
x1 = p1[0] + deltax
else:
C1 = (p1[0]**2 + p1[1]**2 - p0[0]**2 - p0[1]**2) / 2 / (p1[0] - p0[0])
C2 = (p1[1] - p0[1]) / (p1[0] - p0[0])
A = 1 + C2**2
B = 2 * (p0[0] - C1) * C2 - 2*p0[1]
C = (p0[0]-C1)**2 + p0[1]**2 - r**2
y0 = (-B + sqrt(B*B - 4 * A * C)) / 2 / A
y1 = (-B - sqrt(B*B - 4 * A * C)) / 2 / A
x0 = C1 - C2 * y0
x1 = C1 - C2 * y1
return [x0, y0], [x1, y1]
def get_number(self, points, circle, r_squre):
res = 0
for p in points:
dis = self.get_dis(p, circle)
# print(dis, r_squre)
if dis <= r_squre:
res += 1
return res
def numPoints(self, points: [[int]], r: int) -> int:
res = 0
r_squre = r**2
for i in range(len(points)):
for j in range(i+1, len(points)):
dis = self.get_dis(points[i], points[j])
if dis > r_squre*4:
res = max(res, 1)
else:
# print(points[i], points[j])
circle1, circle2 = self.get_circle(points[i], points[j], r)
# print("圆心", circle1, circle2)
res = max(res,
self.get_number(points, circle1, r_squre),
self.get_number(points, circle2, r_squre)
)
return res
# if __name__ == '__main__':
# points = [[-3,0],[3,0],[2,6],[5,4],[0,9],[7,8]]
# r = 5
# points = [[1,2],[3,5],[1,-1],[2,3],[4,1],[1,3]]
# r = 2
# points = [[-2,0],[2,0],[0,2],[0,-2]]
# r = 1
# points = [[-2,0],[2,0],[0,2],[0,-2]]
# r = 2
# print(Solution().get_number(points, [0,4], r**2))
# print(Solution().get_circle([2,4],[4,2],2))
# print(Solution().get_circle([2,4],[4,4],3))
# print(Solution().get_circle([2,4],[2,0],2))
# # print(Solution().get_dis(points[0], points[5]))
# print(Solution().numPoints(points, r))