Leetcode374. Guess Number Higher or Lower

来源:互联网 发布:电动汽车充电软件 编辑:程序博客网 时间:2024/06/01 08:48

题目描述:

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):

-1 : My number is lower     1 : My number is higher     0 : Congrats! You got it!

Example:

    n = 10, I pick 6.    Return 6.

题目含义:

系统在1到n之间随机选择一个数字,让我们猜这个数字,我们猜的比真实的数大时返回1,小于真实的数时返回-1,相等返回0.

解题思路:

这道题属于典型的二分法,对于1到n这n个数,都是进行有序的排列的,那么我们可以直接套用之前二分的公式进行实现。

具体实现:

/* The guess API is defined in the parent class GuessGame.    @param num, your guess    @return -1 if my number is lower, 1 if my number is higher, otherwise return 0    int guess(int num); */    public class Solution extends GuessGame {        public int guessNumber(int n) {            int start = 1;            int end = n;            while (start + 1 < end) {                int mid = start + (end - start)/2;                if (guess(mid) == 0) {                    return mid;                } else if (guess(mid) == -1) {                    end = mid;                } else if (guess(mid) == 1) {                    start = mid;                }            }            if (guess(start) == 0) {                return start;            }            if (guess(end) == 0) {                return end;            }            return -1;            }        }    }   

时间复杂度为O(logn),空间复杂度O(1)。

0 0
原创粉丝点击