C#LeetCode刷题之#374-猜数字大小(Guess Number Higher or Lower)

C#LeetCode刷题之#374-猜数字大小(Guess Number Higher or Lower)

问题

我们正在玩一个猜数字游戏。 游戏规则如下:
我从 1 到 n 选择一个数字。 你需要猜我选择了哪个数字。
每次你猜错了,我会告诉你这个数字是大了还是小了。
你调用一个预先定义好的接口 guess(int num),它会返回 3 个可能的结果(-1,1 或 0):

-1 : 我的数字比较小

1 : 我的数字比较大

 0 : 恭喜!你猜对了!

输入: n = 10, pick = 6

输出: 6

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!

n = 10, I pick 6.

Return 6.

示例

public class Program {

    public static void Main(string[] args) {
        var n = 10;

        var res = GuessNumber(n);
        Console.WriteLine(res);

        Console.ReadKey();
    }

    private static int Guess(int num) {
        return 6.CompareTo(num);
    }

    private static int GuessNumber(int n) {
        //二分法
        var low = 1;
        var high = n;
        var mid = 0;
        while(low <= high) {
            mid = low + (high - low) / 2;
            if(Guess(mid) == 1) {
                low = mid + 1;
            } else if(Guess(mid) == -1) {
                high = mid - 1;
            } else {
                return mid;
            }
        }
        return -1;
    }

}

以上给出1种算法实现,以下是这个案例的输出结果:

6

分析:

显而易见,以上算法的时间复杂度为: O(logn) 。

注:该题没有C#语言的提交,无法AC。

本文由 .Net中文网 原创发布,欢迎大家踊跃转载。

转载请注明本文地址:https://www.byteflying.com/archives/3993

发表评论

登录后才能评论