374. Guess Number Higher or Lower
题意:随机给出一个范围1-n,和一个正确答案pick。
通过一个判断高了还是低了的api,找到你要的答案。
可以抽象为:在一个顺序数组中找到我们要的数值。可用采用二分查找。
我的代码
思路对了, 细节没有处理好。
# The guess API is already defined for you.
# @param num, your guess
# @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
# def guess(num):
class Solution(object):
def guessNumber(self, n):
pick=(n+2)//2
min=1
max=n
while True:
response=guess(pick)
print(response,pick)
if response==1:
min=pick
pick=(pick+1+max)//2
elif response==-1:
max=pick
pick=(pick+min)//2
elif response==0:
return pick
优秀代码
# The guess API is already defined for you.
# @param num, your guess
# @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
# def guess(num):
class Solution(object):
def guessNumber(self, n):
"""
:type n: int
:rtype: int
"""
low, high = 1, n
while True:
mid = low + (high - low) // 2
n = guess(mid)
if n < 0:
high = mid - 1
elif n > 0:
low = mid + 1
else:
return mid
只记录边界,每次取中间值即可。