http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-006-introduction-to-algorithms-fall-2011/python
整個課程分紅8個部分:算法
Lecture 1: Introduction and Peak Finding數組
Peak Finderapp
在數組中找到一個峯值。學習
在數組中,若是b≥c且b≥a,那麼b是一個峯值。若是i≥h,i是一峯值。spa
最簡單的算法就是從數組的第一個元素和它的相鄰的元素比較。算法運行時間爲Θ(n)。code
另外就是使用二分法:orm
算法運行時間爲Θ(log2(n)):ci
Two-dimensional Versionget
在二維數組中若是a ≥ b, a ≥ d, a ≥ c, a ≥ e,那麼a是峯值。
過程以下:
假設二維數組大小爲(m,n),算法運行時間爲Θ(n log n):
python代碼:
def getMaxIndex(sList): #print(sList) iMax = 0 Max = sList[0] for i in range(0,len(sList)): if sList[i] > Max: Max = sList[i] iMax = i return iMax def isPeak(sList,iPos): #print(sList) sLen =len(sList) if(1 == sLen): return 0 elif(sLen - 1 == iPos): if(sList[iPos] < sList[iPos - 1]): return -1 else: return 0 elif(0 == iPos): if(sList[iPos] < sList[iPos + 1]): return 1 else: return 0 elif(sList[iPos] < sList[iPos - 1]): return -1 elif(sList[iPos] < sList[iPos + 1]): return 1 elif(sList[iPos] >= sList[iPos + 1] and sList[iPos] >= sList[iPos - 1]): return 0 def PeakFinder_2D(sList2d,startPos,endPos): rowLen = endPos - startPos + 1 tmpList1 = [] if(0 == rowLen): return -1,-1,-1 iMid = int(rowLen / 2) + startPos colLen = len(sList2d[iMid]) if(0 == colLen): return -1,-1,-1 iMaxValInCol = getMaxIndex(sList2d[iMid]) for i in range(0,len(sList2d[iMid])): tmpList1.append(sList2d[i][iMaxValInCol]) bIsPeak = isPeak(tmpList1, iMid); print(iMid,iMaxValInCol,sList2d[iMid],bIsPeak) if(0 == bIsPeak): return iMid,iMaxValInCol,sList2d[iMid][iMaxValInCol] elif(-1 == bIsPeak) : return PeakFinder_2D(sList2d,startPos,iMid - 1) elif(1 == bIsPeak): return PeakFinder_2D(sList2d,iMid + 1,endPos) return -1,-1,-1