算法基础
一、算法时间复杂度的O(n)和log2n的区别
例如一个print(1) 的时间复杂度 为O(1),那多个print串行呢 结果仍然为O(1)
一个for循环呢 时间复杂度 为O(n) 这个N取决于传入的参数
那logn是如何取呢, 需要 一次循环减半. 就为nlog2n
循环减半的过程 O(logn)
二、常见的时间复杂度排名
O(1) < O(logn) < O(n) < O(nlogn) < O(n2) < O(n2logn) < O(n3)
三、空间复杂度
使用一个变量为O(1)
四、斐波那契数列
递归的效率比较低,因为有重复的子问题
# 1 1 2 3 5 8 13
# 假设小规模的问题能解的条件下,能设计步骤解决原问题
# 重复计算子问题
# def fib(n):
# if n == 0 or n == 1:
# return 1
# else:
# return fib(n-1) + fib(n-2) O(2^n)
# def fib(n):
# res = [1,1]
# for i in range(2, n+1):
# res.append(res[-1] + res[-2])
# return res[-1]
# def fib(n):
# if n == 0 or n == 1:
# return 1
# a = 1
# b = 1
# c = 0
# for i in range(2, n+1):
# c = a + b
# a = b
# b = c
# return c
def fib(n):
res = [0,1,1]
for i in range(2,n+1):
res.pop(0)
res.append(res[-1]+res[-2])
print(res[-1])
print(fib(100))
五、二分法
from timewrap import cal_time
@cal_time
def bin_search(li, val):
low = 0
high = len(li) - 1
while low <= high: # 候选区有值
mid = (low + high) // 2
if li[mid] == val: # 等于证明找到了
return mid
elif li[mid] > val: # 大于val移动high
high = mid - 1
else: # li[mid] < val
low = mid + 1
return -1
@cal_time
def bin_search_rec(data_set,value,low,high):
# 递归查找的二分法
if low <= high:
mid = (low + high) // 2
if data_set[mid] == value:
return mid
elif data_set[mid] > value:
return bin_search_rec(data_set,value,low,mid-1)
else:
return bin_search_rec(data_set,value,mid+1,high)
else:
return
@cal_time
def sys_search(li, val):
try:
return li.index(val)
except:
return -1
li = list(range(0,100,2))
bin_search(li, 6)
sys_search(li,6)
bin_search_rec(li,6,0,99)
使用一个列表 O(n)
使用一个二维数组 O(n2)

浙公网安备 33010602011771号