小魚要學數據結構(基於python)—Day1算法分析

數據結構學習筆記(北大公開課)

算法分析

下面是這一課的知識點概覽,首先介紹了大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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章