题目:
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%)
那我们下题见