• 寻找数组中最接近目标的数字


    要寻找数组中最接近目标的数字,你可以使用一种称为线性搜索或二分搜索的方法,具体取决于数组是否已排序。以下是这两种方法的示例:

    1. 线性搜索(未排序数组):

    如果数组未排序,你可以使用线性搜索来查找最接近目标的数字。这个方法将遍历整个数组,找到与目标最接近的数字。

    def find_closest_number(arr, target):

        closest = arr[0]

        min_difference = abs(target - arr[0])

       

        for num in arr:

            difference = abs(target - num)

           

            if difference < min_difference:

                min_difference = difference

                closest = num

       

    return closest

    示例用法:

    arr = [4, 7, 12, 15, 18]

    target = 9

    result = find_closest_number(arr, target)

    print("最接近的数字是:", result)

    二分搜索(已排序数组):

    如果数组已排序,你可以使用二分搜索来更有效地找到最接近目标的数字。

    def binary_search_closest(arr, target):

        low = 0

        high = len(arr) - 1

       

        while low <= high:

            mid = (low + high) // 2

           

            if arr[mid] == target:

                return arr[mid]

            elif arr[mid] < target:

                low = mid + 1

            else:

                high = mid - 1

       

        # 找到最接近的数字

        if abs(arr[low] - target) < abs(arr[high] - target):

            return arr[low]

        else:

            return arr[high]

    示例用法:

    arr = [2, 5, 8, 12, 17, 19, 22]

    target = 10

    result = binary_search_closest(arr, target)

    print("最接近的数字是:", result)

    这两种方法分别适用于已排序和未排序的数组。根据你的需求选择其中一种方法。

  • 相关阅读:
    C/C++超市收银系统
    面向对象之抽象类的认识 - (java语法)
    前端css实现特殊日期网页变灰功能
    block 归纳总结 上
    有意识的神经网络之对比网络层和后意识层 加入em
    仿真-Carla-控制方法原理流程研究
    VR全景图比平面图多了哪些优势,VR全景可以用在哪些领域
    python 小案例76
    uniapp 使用svg
    CentOS Linux 的安装
  • 原文地址:https://blog.csdn.net/sun13212715744/article/details/133962647