1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| public static void main(String[] args) { Boolean[] balls = new Boolean[] { false, false, false, false, true, false, false System.out.println("已知的空球为:" + balls[4].hashCode()); searchBall(balls, true); }
public static void searchBall(Boolean[] balls, boolean findValue) { System.out.println("称重....."); if (balls == null) { return; } int size = 0; int indexSize = 0; if (balls.length % 2 != 0) { size = balls.length - 1; } else { size = balls.length; } indexSize = size / 2; Boolean[] preBalls = Arrays.copyOfRange(balls, 0, indexSize); Boolean[] lastBalls = Arrays.copyOfRange(balls, indexSize, size); int weight1 = getWeight(preBalls); int weight2 = getWeight(lastBalls); if (weight1 == weight2) { System.out.println("已找到不同的球:" + balls[balls.length - 1].hashCode()); } else if (weight1 > weight2) { if (lastBalls.length == 1) { System.out.println("已找到不同的球::" + lastBalls[0].hashCode()); return; } searchBall(lastBalls, findValue); } else { if (preBalls.length == 1) { System.out.println("已找到不同的球::" + lastBalls[0].hashCode()); return; } searchBall(preBalls, findValue); } }
public static int getWeight(Boolean[] balls) { int count = 0; for (boolean b : balls) { if (!b) { count++; } } return count; }
|