数据结构算法--1 顺序查找二分查找

顺序查找时间复杂度为O(n)

我们可以借助Python中的函数enumerate,通过enumerate遍历列表返回其索引和值

python 复制代码
def linnear_search(li, val):
    for ind, v in enumerate(li):
        if v == val:
            return ind
    else:
        return None

也可以通过列表长度依次遍历:

python 复制代码
def linear_search(li, val):     # 顺序查找复杂度为O(n)
    for i in range(len(li)):
        if li[i]==val:
            return i
    return

O(1)<O(logn)<O(n)<O(nlogn)<O(n*n)

但是二分查找时间复杂度为O(logn):

python 复制代码
def binary_search(li,val):
    left=0
    right=len(li)-1
    while left<=right:
        mid=(left+right) // 2
        if li[mid]==val:    # 最后会找到mid
            return mid
        elif li[mid]>val:   # mid值大与查找值,就需要去左半侧查找,right指针就改变
            right=mid-1
        else:
            left=mid+1
    else:
        return None
相关推荐
JieE2129 小时前
LeetCode 101. 对称二叉树|JS 递归 + 迭代双解法,彻底搞懂镜像判断
javascript·算法
金銀銅鐵14 小时前
[Python] 从《千字文》中随机挑选汉字
后端·python
cup1118 小时前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi0020 小时前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵1 天前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf1 天前
Agent 流程编排
后端·python·agent
copyer_xyf1 天前
Agent RAG
后端·python·agent
copyer_xyf1 天前
【RAG】向量数据库:milvus
后端·python·agent
copyer_xyf1 天前
Agent 记忆管理
后端·python·agent