[LeetCode] 374. Guess Number Higher or Lower
Posted aaronliu1991
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 374. Guess Number Higher or Lower相关的知识,希望对你有一定的参考价值。
这也是一个通过二分法调用API猜数字大小的题目。注意判断的边界是从1到N。这题没有提供javascript的API所以我就直接上Java的代码了。
时间O(logn)
空间O(1)
1 /* The guess API is defined in the parent class GuessGame. 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 6 public class Solution extends GuessGame { 7 public int guessNumber(int n) { 8 int start = 1; 9 int end = n; 10 while (start + 1 < end) { 11 int mid = start + (end - start) / 2; 12 if (guess(mid) == 0) { 13 return mid; 14 } else if (guess(mid) == 1) { 15 start = mid; 16 } else { 17 end = mid; 18 } 19 } 20 if (guess(start) == 0) return start; 21 return end; 22 } 23 }
以上是关于[LeetCode] 374. Guess Number Higher or Lower的主要内容,如果未能解决你的问题,请参考以下文章
[leetcode] 374. Guess Number Higher or Lower
LeetCode 374. Guess Number Higher or Lower
Leetcode 374. Guess Number Higher or Lower
leetcode 374. Guess Number Higher or Lower