0%

guess-number-higher-or-lower

Guess Number Higher or Lower – LeetCode 374

Problem

Description

We are playing the Guess Game. The game is as follows:

I pick a number from 1 to n. You have to guess which number I picked.

Every time you guess wrong, I’ll tell you whether the number is higher or lower.

You call a pre-defined API guess(int num) which returns 3 possible results (-1, 1, or 0):

Example

n = 10, I pick 6.

Return 6.

Answer

Original

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// Forward declaration of guess API.
// @param num, your guess
// @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
int guess(int num);

class Solution {
public:
int guessNumber(int n) {
int l = 1, r = n;
while(l <= r){
int m = l + (r - l) / 2;
int res = guess(m);
if(res == 1)
l = m + 1;
else if(res == -1)
r = m - 1;
else
return m;
}
}
};

思路

简单使用二分查找。时间复杂度$O(log_{2}{n})$,空间复杂度$O(1)$。
耗时$2$ ms,排名$81.30\%$

Better

思路

看到题解中有三分查找。时间复杂度$O(log_{3}{n})$,空间复杂度$O(1)$。
耗时$2$ ms,排名$81.30\%$

Code

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
// Forward declaration of guess API.
// @param num, your guess
// @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
int guess(int num);

class Solution {
public:
int guessNumber(int n) {
int l = 1, r = n;
while(l <= r){
int m1 = l + (r - l) / 3;
int m2 = r - (r - l) / 3;
int r1 = guess(m1);
int r2 = guess(m2);
if(!r1) return m1;
if(!r2) return m2;
if(r1 < 0)
r = m1 - 1;
else if(r2 > 0)
l = m2 + 1;
else {
l = m1 + 1;
r = m2 - 1;
}
}
}
};