zoukankan      html  css  js  c++  java
  • 算法--练习题1

    思路:利用二分法求解

    def bin_search(data_set,val):
        low = 0
        high = len(data_set) - 1
        while low <= high:
            mid = (low + high) // 2 # 求中间值
            if data_set[mid] == val: # 输入值和中间值相等
                left = mid # 左边值为中间值
                right = mid # 右边值为中间值
                while left >= 0 and data_set[left] == val: # 左边值大于 0 ,左边值为选定的值
                    left -= 1 # 向左边递进
                while right <= high and data_set[right] == val: # 右边值需要小于最右边的值 且 右边值 为 选定值
                    right += 1 # 向右 递进
                return (left +1 , right - 1 )
            elif data_set[mid] < val: # 选定值 大于中间值
                low = mid + 1 # low 为 中间值 +1
            else: # 选定值 小于 中间值
                high = mid - 1 # high 为 中间值 - 1
        return
    
    li = [1,2,3,3,3,4,4,5]
    print(bin_search(li,4))

    显示结果为:

  • 相关阅读:
    异步I/O
    path路径操作
    Buffer类
    ES6常用语法
    GitHub上的基本功能与概念
    git的基本命令
    HTML中的表单
    PyCharm的安装以及破解
    HTML中的表格
    HTML中的列表
  • 原文地址:https://www.cnblogs.com/zhuifeng-mayi/p/9220914.html
Copyright © 2011-2022 走看看