查找一个有序数列中的一个数是否存在的方法

lis = [2,4,6,7]
n = 3
lst = [0,0,0,0,0,0,0]   #创建一个元素均为0的列表,元素个数为lis中最大的数字加1
li = [0,0,1,0,1,0,1,1]  #把 lis 中对应的数字值变为1
if li[3] == 1:
    print("存在")
else:
    print("不存在")

主要思想为,新建列表作为索引,如果一个数的索引存在,说明这个数也存在.

这种查找方法主要是为了能够节省时间和空间.

也可以把lst 做成字典,如

lis = [2,4,6,7]
n = 3
dic = {"2":1,"4":1,"6":1,"7":1}
if dic.get("3") == 1:
    print("存在")
else:
    print("不存在")

显而易见的是,字典更占用内存,即空间.

猜你喜欢

转载自www.cnblogs.com/cuiyuanzhang/p/9483528.html