瓶子问题 [M$面试题]
Problem Set: 有12个瓶子, 其中有一个与其它瓶子重量不同.现在有一架天平,试用三次天平找出这个瓶子.
Prob Sloved: 我的思路是, 将12个瓶子分为四堆,选出一个不同重量的堆,然后从这个堆中,找出这个瓶子。
1
import java.util.*;
2
public class WeightBottle
3
{
4
public static int selectBottle(int []array)
5
{
6
int index =0;
7
int len = array.length;
8
int []a = new int[4];
9
for(int i=0; i<4; i++)
10
{
11
for(int j=0; j<len; j++)
12
{
13
a[i] += array[j%3 + i*3];
14
}
15
}
16
17
int numOfPart =0;
18
for(int i=0; i<4; i++)
19
{
20
if(i+1<4 && a[i] != a[i+1])
21
{
22
numOfPart = i;
23
//System.out.println(a[i]+" "+a[i+1]);
24
}
25
//System.out.println(" "+a[i]);
26
}
27
//找到哪一堆的瓶子
28
int count1 = 0;
29
int count2 = 0;
30
for(int i=0; i<4; i++)
31
{
32
if(a[numOfPart] != a[i]) count1 ++;
33
if(a[numOfPart+1] != a[i]) count2 ++;
34
if(count1 ==3) //则numOfPart堆的瓶子有问题
35
{
36
break;
37
}
38
if(count2 ==3) //则numOfPart堆的瓶子有问题
39
{
40
numOfPart = numOfPart+1;
41
break;
42
}
43
}
44
45
for(int i=0; i<3; i++)
46
{
47
if(array[numOfPart*3+i%3] != array[numOfPart*3+i%3 +1])
48
{
49
index = numOfPart*3+i%3;
50
break;
51
}
52
}
53
if(index+1<12 && array[index]==array[index+2]) index = index +1;
54
else if(index+1==12 && array[index] == array[index -1]) index = index +1;
55
56
return index;
57
}
58
59
public static void main(String[] args)
60
{
61
Random rand=new Random();
62
int randNum = Math.abs(rand.nextInt())%12+1;
63
64
//随机产生12个瓶子的重量
65
int []array = new int [12];
66
for(int i=0; i<12; i++)
67
{
68
array[i] = randNum;
69
}
70
int n = Math.abs(rand.nextInt())%12;
71
array[n] = randNum*randNum+2;
72
System.out.println("输出十二个瓶子的重量:");
73
for(int i=0; i<12; i++)
74
{
75
System.out.println((i+1)+": "+array[i]);
76
}
77
//找出这个不同的瓶子
78
int index = selectBottle(array);
79
System.out.println("这个瓶子是第"+(index+1)+"个!");
80
}
81
}
82

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

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步