数据结构学习笔记(北大公开课)
算法分析
下面是这一课的知识点概览,首先介绍了大O记号的七种级别的复杂度。
下面是这一课相关的代码实践
累计求和
两种方法对比:用time计时
##累计求和
#迭代
import time
def sumofn(n):
start=time.time()
theSum=0
for i in range(1,n+1):
theSum=theSum+i
end=time.time()
return theSum,end-start
#print(sumofn(10))
#for i in range(5):
# print('sum is %d required %10.7f seconds'%sumofn(100000))
#无迭代
def sumofn3(n):
start=time.time()
thesum=(n*(n+1))/2
end=time.time()
return thesum,end-start
#for i in range(5):
# print('sum is %d required %10.7f seconds'%sumofn3(100000))
变位词判断问题
四种方法复杂度对比(暴力解法没写)
##变位词判断问题
#逐字检查
def anagramSolution(s1,s2):
alist=list(s2)
pos1=0
stillOK=True
while pos1<len(s1) and stillOK:#循环s1中的每一个字符
pos2=0
found=False
while pos2<len(alist) and not found:
if s1[pos1]==alist[pos2]:
found=True
else:
pos2=pos2+1
if found:
alist[pos2]=None
else:
stillOK=False
pos1=pos1+1
return stillOK
#print(anagramSolution('abcd','dcba'))
#排序解法
def anagramSolution2(s1,s2):
alist1=list(s1)
alist2=list(s2)
alist1.sort()
alist2.sort()
pos=0
matches=True
while pos<len(s1) and matches:
if alist1[pos]==alist2[pos]:
pos=pos+1
else:
matches=False
return matches
print(anagramSolution2('abcd','dcba'))
#计数器解法
def anagramSolution3(s1,s2):
c1=[0]*26
c2=[0]*26
for i in range(len(s1)):
pos=ord(s1[i])-ord('a')#把a-z转化为0-25 ps:感谢m0_47550366的提醒,此处错误已改正
c1[pos]=c1[pos]+1#计数
for i in range(len(s2)):
pos = ord(s2[i]) - ord('a') # 把a-z转化为0-25
c2[pos] = c2[pos] + 1 # 计数
j=0
stillOK=True
while j<26 and stillOK:
if c1[j]==c2[j]:
j=j+1
else:
stillOK=False
return stillOK
print(anagramSolution3('abcd','dcba'))
输出
True
True