LeetCode刷题笔记
时间:5月25日
内容:小A 和 小B 在玩猜数字。小B 每次从 1, 2, 3 中随机选择一个,小A 每次也从 1, 2, 3 中选择一个猜。他们一共进行三次这个游戏,请返回 小A 猜对了几次?
思路:分别比较两个数组中的每个元素
1 public int game(int[] guess, int[] answer) {
2 int count = 0;
3
4 // 判断是否是3个
5 if ((guess.length == 3) && (answer.length == 3)) {
6 //循环鉴定,记录相同次数
7 for (int i = 0; i < 3; i++) {
8 if (guess[i] == answer[i]) {
9 count = count + 1;
10 }
11 }
12 return count;
13
14 }
15 System.out.println("输入数据错误");
16 return count;
17 }
18
19 /**
20 * 随机排列数组
21 *
22 * @param arr
23 * @return
24 */
25 public int[] radomNumber(int[] arr) {
26 int rnd;
27 for (int i = 0; i < arr.length; i++) {
28 rnd = new Random().nextInt(4);
29 while (rnd == 0) {
30 rnd = new Random().nextInt(4);
31 }
32 arr[i] = rnd;
33 }
34 return arr;
35 }