1: // Forward declaration of guess API.
2: // @param num, your guess
3: // @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
4: int guess(int num);
5: class Solution {
6: public:
7: int guessNumber(int n) {
8: int l = 1, r = n, mid = 0, res = 0;
9: while (l <= r) {
10: mid = l + (r-l) /2;
11: res = guess(mid);
12: if (res == 0) return mid;
13: else if (res == 1) l = mid + 1;
14: else r = mid - 1;
15: }
16: return mid;
17: }
18: };
Saturday, July 16, 2016
374. Guess Number Higher or Lower
A typical binary search.
Labels:
binary search,
google,
leetcode
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment