21. 移动的圆
题目将给出两个圆A和B的圆心坐标(x,y)和半径r,现给你一个点P,使圆A圆心沿直线运动至点P。
请问圆A在运动过程中是否会与圆B相交?(运动过程包括起点和终点)
若会相交返回1,否则返回-1。
样例
样例 1
输入:[0,0,2.5,3,2,0.5,0,2]
输出:1
样例解释:圆A的圆心(0,0),半径为2.5,圆B的圆心(3,2),半径为0.5,点P(0,2),如图:
样例 2
输入:[0,0,2,5,0,1,0,2]
输出:-1
样例解释:圆A的圆心(0,0),半径为2,圆B的圆心(5,0),半径为1,点P(0,2)
注意事项
两个圆的半径均不超过10000。
横纵坐标值的绝对值均不超过10000。
public class Solution {
/**
* @param position: the position of circle A,B and point P.
* @return: if two circle intersect return 1, otherwise -1.
*/
public int IfIntersect(double[] position) {
double x3 = position[0];
double y3 = position[1];
double aR = position[2];
double x1 = position[3];
double y1 = position[4];
double bR = position[5];
double x2 = position[6];
double y2 = position[7];
double sumR = aR + bR;
double sumR2 =aR - bR;
double r = 0;
double flag = 100d;//最小可以20
// System.out.println(sumR+","+sumR2);
double x23 = (x2 - x3) / flag;
double y23 = (y2 - y3) / flag;
for (int i = 0; i <= flag; i++) {
double v = x3 + x23* i - x1;
double z = y3 + y23* i - y1;
r = Math.sqrt(v * v + z * z);
// System.out.println(v+","+z+"="+r);
if (r <= sumR && r >= sumR2) return 1;
}
return -1;
}
}