1.跳台阶扩展问题
class Solution:
def jumpFloorII(self , number: int) -> int:
# write code here
# n阶台阶,可以设想,最后一步为一步跳、两步跳、三步跳等
# 可以列出等式f(n) = f(n-1) + f(n-2) +...+ f(1)
# 此方法为图中粉红色
res = 1
for i in range(1, number):
res = res * 2
return res
# 此方法为图中灰色
return pow(2,number-1)
2.买卖股票的最好时机(一)
class Solution:
def maxProfit(self , prices: List[int]) -> int:
# write code here
# 利用之前动态规划的思想,使用res始终保存能够获得的最大利润
# 根据题意,我们需要在买入时是最低价,卖出时为最低价后面的最大值
# 因此最低价也是需要记录保存的数值,比如[8,9,2,5,4,7,1],如果我们始终使用8作为最低价,我们就会错过后面的2
# 因此遇到比8更小的价,我们就马上将其作为买入时间节点。
# 可能会担心把最低价换了,后来发现后面的没有可以赚的时间了,没关系,我们的res已经替我们保存好着历史最高利润
res = 0
min_ = prices[0]
for i in range(1, len(prices)):
temp = prices[i] - min_
if res <= temp:
res = temp
if prices[i] < min_:
min_ = prices[i]
return res
3.数组中重复的数字
class Solution:
def duplicate(self , numbers: List[int]) -> int:
# write code here
# 另取字典存储每个数字有多少个,两个遍历,一次遍历数组,一次遍历字典
count_dict = {}
for num in numbers:
if num not in count_dict.keys():
count_dict[num] = 1
continue
count_dict[num] += 1
for k,v in count_dict.items():
if v > 1:
return k
return -1
4. 不用加减乘除做加法
class Solution:
def Add(self , num1: int, num2: int) -> int:
# write code here
return sum([num1,num2])
# 看不懂的位运算方法
x = 0xffffffff
num1 = num1 & x
num2 = num2 & x
a, b = num1, num2
while b != 0:
a, b = a ^ b, (a & b) << 1 & x
return a if a <= 0x7fffffff else ~(a ^ x)