#50 Pow(x, n) (Easy)
Implement pow(x, n), which calculates
x
raised to the powern
(i.e.,xn
).
解法:
不知道和二分查找有什么关系?感觉就是直接算?(后来知道了……
class Solution:
def myPow(self, x: float, n: int) -> float:
if n < 0:
x, n = 1/x, -n
if n == 0:
return 1
return x**n
runtime:
尴尬,超级慢……
看看16ms的solution:
这个用的是recursive的算法。
Q: 为什么这样比我的要快?
A:我用的是brute force。Time complexity是O(n), x 乘了n次,所以慢。helper就把相乘的次数直接减半。所以time complexity是O(log n)。
#367 Valid Perfect Square (Easy)
Given a positive integer num, write a function which returns True if num is a perfect square else False.
Follow up: Do not use any built-in library function such as
sqrt
.
解题思路:
找到num的开方根,寻找范围是(num/(2^n))<num<(num/(2^(n-1)))。剩下最后一个值看其平方是不是num,不是则False,是则True。
class Solution:
def isPerfectSquare(self, num: int) -> bool:
if num == 1:
return True
left = num//2
val = left*left
while val > num:
left //= 2
val = left*left
# now the real root is between left and left*2
right = left * 2
while left < right:
root = (left+right)//2
val = root*root
if val > num:
right = root
elif val < num:
left = root + 1
else:
return True
if left*left == num:
return Ture
else:
return False
runtime:
16ms solution:
我找开方根的思路相当于多此一举。直接头尾取中来找。
重新写了一遍,right设为num//2。
class Solution:
def isPerfectSquare(self, num: int) -> bool:
left, right = 1, num//2
while left <= right:
root = left+ (right-left)//2
val = root*root
if val == num:
return True
elif val < num:
left = root + 1
else:
right = root -1
if left*left == num:
return True
else:
return False
runtime:
#744 Find Smallest Letter Greater Than Target (Easy)
Given a characters array
letters
that is sorted in non-decreasing order and a charactertarget
, return the smallest character in the array that is larger thantarget
.Note that the letters wrap around.
- For example, if
target == 'z'
andletters == ['a', 'b']
, the answer is'a'
.
解题思路:
用bisect求出最右应加入位置index,如果是最后一位,那么index就取0。
class Solution:
def nextGreatestLetter(self, letters: List[str], target: str) -> str:
index = bisect.bisect(letters, target)
return letters[index % len(letters)]
用取余数可以解决这个问题。
runtime:
Apr 1st复习的时候,按照对二分搜索的理解再做了一遍:
class Solution:
def nextGreatestLetter(self, letters: List[str], target: str) -> str:
l, r = 0, len(letters)-1
while l<r:
m = (l+r)//2
if letters[m] > target:
r = m
else:
l = m + 1
if letters[l] <= target:
if l == len(letters)-1:
return letters[0]
else:
return letters[l+1]
return letters[l]
runtime:
有小小进步:)就是处理特殊情况的时候,post process要很小心,容易出错。如果最后出来的位置,不是target,那么直接输出。如果是,又不在队尾,就+1;在队尾,就回头是0。