Posted on 2022-11-16 14:04
Uriel 阅读(43)
评论(0) 编辑 收藏 引用 所属分类:
闲来无事重切Leet Code 、
二分.三分
猜数字游戏,给定范围1-n,每次调用guess函数,按照返回值判断猜高了还是低了还是正确,输出选中的数字,简单二分
1 #374
2 #Runtime: 42 ms
3 #Memory Usage: 13.3 MB
4
5 # The guess API is already defined for you.
6 # @param num, your guess
7 # @return -1 if num is higher than the picked number
8 # 1 if num is lower than the picked number
9 # otherwise return 0
10 # def guess(num):
11
12 class Solution(object):
13 def guessNumber(self, n):
14 """
15 :type n: int
16 :rtype: int
17 """
18 l = 1
19 r = n
20 while l < r:
21 mid = (l + r) // 2
22 if guess(mid) == 1:
23 l = mid + 1
24 elif guess(mid) == 0:
25 return mid
26 else:
27 r = mid - 1
28 return l