62,634
社区成员




public class Ball {
public int[] balls;
public Ball(int N) {
balls = new int[N];
for (int i = 0; i < N; i++) {
balls[i] = 100;
}
// 随机生成非标准球
balls[Integer.parseInt(Math.round(N * Math.random() * 10) + "") / 10] = 999;
for (int i = 0; i < N; i++) {
System.out.print(balls[i] + ",");
}
System.out.println();
}
}
public class MainTest {
public static void main(String[] args) {
MainTest test = new MainTest();
Ball ball = new Ball(50);
System.out.println("非标准球:" + test.findBall(ball.balls) + " 次数:" + times);
}
// 记录标准重
private int standardWight = -1;
// 遍历次数,每使用天平一次加1
private static int times = 0;
// 递归查找
private int findBall(int[] balls) {
// 只剩最后一个球则一定是非标准球
if (balls.length == 1) return standardWight;
times++;
// 如果是两个球
if (balls.length == 2) {
if (balls[0] == balls[1]) {
return 0;
}
return standardWight == balls[0] ? balls[1] : balls[0];
}
// 折半找中间轴
int middle = balls.length / 2 + balls.length % 2;
if (middle % 2 == 1) middle += 1;
int endPos = middle / 2;
// 判断左半部分是否有非标准球
if (sumWeight(balls, 0, endPos - 1) == sumWeight(balls, endPos, endPos * 2 - 1)) {
standardWight = balls[0];
// if (middle % 2 == 1) {
// times++;
// if (balls[middle - 1] != balls[0]) return balls[middle - 1];
// }
return findBall(getFocusBall(balls, middle, balls.length));
// 判断是否只有3个球,且有非标准球的情况
} else if (middle == 3) {
times++;
return balls[1] == balls[2] ? balls[0] : balls[1];
} else {
// 判断右半部分是否有非标准球
standardWight = balls[middle];
return findBall(getFocusBall(balls, 0, middle));
}
}
private static int sumWeight(int[] balls, int startPos, int endPos) {
int total = 0;
for (int i = startPos; i <= endPos; i++) {
total += balls[i];
}
return total;
}
/**
* 生成新的目标球
* @param balls
* @param startPos
* @param endPos
* @return
*/
private int[] getFocusBall(int[] balls, int startPos, int endPos) {
int[] focusBall = new int[endPos - startPos];
System.out.println("生成新的目标球 起始下标:" + startPos + " 终止坐标:" + (endPos - 1));
for (int i = 0; i < focusBall.length; i++) {
focusBall[i] = balls[i + startPos];
System.out.print(focusBall[i] + ",");
}
System.out.println();
return focusBall;
}
}
随机输出结果:
100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,999,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,
生成新的目标球 起始下标:26 终止坐标:49
100,100,999,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,
生成新的目标球 起始下标:0 终止坐标:11
100,100,999,100,100,100,100,100,100,100,100,100,
生成新的目标球 起始下标:0 终止坐标:5
100,100,999,100,100,100,
生成新的目标球 起始下标:0 终止坐标:3
100,100,999,100,
生成新的目标球 起始下标:2 终止坐标:3
999,100,
非标准球:999 次数:6