https://leetcode.com/problems/guess-number-higher-or-lower/ 这道题我以为很简单,用二分法写了一下,但执行时候报超时(而且为了增加效率我把除法改成了位运算),我自己拿到 pycharm 里试了一下没问题。不知道是哪段代码让 leetcode 不能通过的。
def guessNumber(self, n):
"""
:type n: int
:rtype: int
"""
if n < 2:
return n
deep = 1
x = n >> deep
while 1:
result = guess(x)
deep += 1
if result < 0:
x = x + (n >> deep)
elif result > 0:
x = x - (n >> deep)
else:
return x
1
holyghost 2016-11-22 20:15:28 +08:00 via iPhone
有一个 case 死循环了吧
|
2
yangff 2016-11-22 20:17:26 +08:00
-1 : My number is lower
1 : My number is higher 0 : Congrats! You got it! |
3
woostundy OP ```
def guessNumber(self, n): """ :type n: int :rtype: int """ if n < 2: return n low = 1 high = n while 1: x = (low + high) / 2 result = guess(x) if result < 0: low = x - 1 elif result > 0: high = x + 1 else: return x ``` 换了一种方式,然并卵啊,依然不好使。 问题是这俩写法我在 pycharm 里都是正常的 |
4
finab 2016-11-22 20:21:12 +08:00 via iPhone
还是 java 写省事,我有个算法用 Swift 写的,死活过不去,报超时。后来用 java 写一遍,算法都一样,通过了。
|
5
Mistwave 2016-11-22 20:28:48 +08:00 via iPhone
guess(x) 是什么?
|
6
woostundy OP @Mistwave 预定义的一个函数,返回你猜的数字:
-1 : My number is lower 1 : My number is higher 0 : Congrats! You got it! |
10
lonelinsky 2016-11-22 21:51:52 +08:00
二分逻辑写错了,注意 guess 的定义,简单改了下
``` class Solution(object): def guessNumber(self, n): """ :type n: int :rtype: int """ if n < 2: return n low = 1 high = n while 1: x = (low + high) // 2 result = guess(x) if result < 0: high = x - 1 elif result > 0: low = x + 1 else: return x ``` |
11
woostundy OP @lonelinsky ...多谢,我把 guess 的定义看反了
|
12
woostundy OP |
13
woostundy OP 第一种写法最终的答案应该是这样
``` def guessNumber(self, n): """ :type n: int :rtype: int """ if n < 2: return n deep = 1 x = n >> deep while 1: result = guess(x) deep += 1 if result > 0: x = x + (n >> deep) + 1 elif result < 0: x = x - (n >> deep) - 1 else: return x ``` |
14
raytlty 2016-11-23 22:39:19 +08:00
```
lhs, rhs = 1, n while lhs < rhs: mid = (lhs + rhs) >> 1 lhs, rhs = [(mid, mid), (mid+1, rhs), (lhs, mid-1)][guess(mid)] ``` |
16
jedihy 2016-12-22 01:02:31 +08:00
python 位运算并不比除法快。
|