File tree Expand file tree Collapse file tree 1 file changed +63
-0
lines changed
Expand file tree Collapse file tree 1 file changed +63
-0
lines changed Original file line number Diff line number Diff line change 1+ /*
2+ * @lc app=leetcode.cn id=374 lang=java
3+ *
4+ * [374] 猜数字大小
5+ *
6+ * https://leetcode-cn.com/problems/guess-number-higher-or-lower/description/
7+ *
8+ * algorithms
9+ * Easy (44.17%)
10+ * Likes: 64
11+ * Dislikes: 0
12+ * Total Accepted: 25.7K
13+ * Total Submissions: 57.5K
14+ * Testcase Example: '10\n6'
15+ *
16+ * 我们正在玩一个猜数字游戏。 游戏规则如下:
17+ * 我从 1 到 n 选择一个数字。 你需要猜我选择了哪个数字。
18+ * 每次你猜错了,我会告诉你这个数字是大了还是小了。
19+ * 你调用一个预先定义好的接口 guess(int num),它会返回 3 个可能的结果(-1,1 或 0):
20+ *
21+ * -1 : 我的数字比较小
22+ * 1 : 我的数字比较大
23+ * 0 : 恭喜!你猜对了!
24+ *
25+ *
26+ *
27+ *
28+ * 示例 :
29+ *
30+ * 输入: n = 10, pick = 6
31+ * 输出: 6
32+ *
33+ */
34+
35+ // @lc code=start
36+ /**
37+ * Forward declaration of guess API.
38+ * @param num your guess
39+ * @return -1 if num is lower than the guess number
40+ * 1 if num is higher than the guess number
41+ * otherwise return 0
42+ * int guess(int num);
43+ */
44+
45+ public class Solution extends GuessGame {
46+ public int guessNumber (int n ) {
47+ int left = 1 ;
48+ int right = n ;
49+ while (left <= right ) {
50+ int mid = left + (right - left ) / 2 ;
51+ if (guess (mid ) == -1 ) {
52+ right = mid - 1 ;
53+ } else if (guess (mid ) == 1 ) {
54+ left = mid + 1 ;
55+ } else if (guess (mid ) == 0 ) {
56+ return mid ;
57+ }
58+ }
59+ return -1 ;
60+ }
61+ }
62+ // @lc code=end
63+
You can’t perform that action at this time.
0 commit comments