leetcode with python:374. Guess Number Higher or Lower

题目:

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 will tell you whether the number I picked is higher or lower than your guess.

You call a pre-defined API int guess(int num), which returns three possible results:

-1: Your guess is higher than the number I picked (i.e. num > pick).
1: Your guess is lower than the number I picked (i.e. num < pick).
0: your guess is equal to the number I picked (i.e. num == pick).
Return the number that I picked.

给定一数n,题目会在1~n的範围选一个目标数(target)
题目有提供函数guess(x)来判断target和x的关係
若x>target,回传-1
x< target,回传1
x==target,回传0
透过该函数推测并回传target

这题基本上就是在和题目玩终极密码(一个充斥二分搜要素的儿时游戏)

# The guess API is already defined for you.# @param num, your guess# @return -1 if num is higher than the picked number#          1 if num is lower than the picked number#          otherwise return 0# def guess(num: int) -> int:class Solution:    def guessNumber(self, n: int) -> int:        l=1        r=n        while l<=r:            mid=(l+r)//2            if guess(mid)==1:                l=mid+1            elif guess(mid)==-1:                r=mid-1            else:                return mid

在1~n的範围进行二分搜
设下限l=1跟上限r=n,mid定义为(1+r)//2
若guess(mid)等于1(mid< target),l提高到mid+1
若guess(mid)等于-1(mid>target),r降低到mid-1
一旦guess(mid)等于0就回传mid(猜中了)
最后执行时间31ms(faster than 91.30%)

那我们下题见


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章