- 论坛徽章:
- 0
|
试着回一贴。
#!/usr/bin/env python
#coding=utf-8
import time
"""全局变量"""
numList = []
maxnum = 0
headtag = 0
tailtag = 0
midtag = 0
def SearchNum(missingnum):
"""递归折半查找
"""
global headtag
global tailtag
global midtag
#print headtag,midtag,tailtag
if tailtag - headtag < 3:
if numList[headtag] != headtag + 1:
missingnum.append(headtag + 1)
midtag = headtag
return 0
elif numList[midtag] != midtag + 1:
missingnum.append(midtag + 1)
return 0
else:
missingnum.append(tailtag + 1)
midtag = tailtag
return 0
if numList[midtag] == midtag + 1:
headtag = midtag
midtag = int((headtag + tailtag) / 2)
SearchNum(missingnum)
elif numList[midtag] > midtag + 1:
tailtag = midtag
midtag = int((headtag + tailtag) / 2)
SearchNum(missingnum)
def SetNumList():
"""初始化数据
"""
global numList
global maxnum
global headtag
global tailtag
global midtag
numList = range(1,1000001)
maxnum = len(numList)
numList.remove(3434)
numList.remove(607068)
headtag = 0
tailtag = len(numList) - 1
midtag = int(tailtag / 2)
def InsertNumList(position,num):
"""插入缺失数
"""
global numList
numList.insert(position,num)
def ResetGlobalParam():
"""重置标志位
"""
global headtag
global tailtag
global midtag
headtag = 0
tailtag = maxnum - 1
midtag = int(tailtag / 2)
if __name__ == "__main__":
print "Method 1"
SetNumList()
beginTime = time.time()
missingnum = []
SearchNum(missingnum)
#print missingnum
#print midtag
InsertNumList(midtag,missingnum[0])
ResetGlobalParam()
SearchNum(missingnum)
print missingnum
#print midtag
endTime = time.time()
print endTime - beginTime |
|
|