You need to enable JavaScript to run this app. 基于numpy在单峰列表中快速查找目标值的两侧最近匹配值
优惠活动
大模型
产品
解决方案
定价
更多

基于numpy在单峰列表中快速查找目标值的两侧最近匹配值

单峰数组双侧最近匹配值的高效实现方案

针对单峰形态数组的双侧最近值查找需求,可依托数组的单调分段特性针对性优化,相比现有全量遍历的方案效率提升数个量级,核心逻辑如下:

  • 利用单峰数组的结构特性:从数组起点到峰值段严格递增、从峰值段到数组末尾严格递减,两个分段天然满足单调有序要求,完全可以用二分查找替代全量遍历找近邻,将查找环节的时间复杂度从O(n)降到O(logn),数组长度越长效率优势越显著
  • 峰值定位仅做一次全局扫描:单峰数组的峰值就是全局最大值,直接通过np.argmax定位峰值索引即可,避免冗余的重复索引查找
  • 所有操作适配numpy底层C实现:没有Python层的循环开销,最大化减少运行时的额外损耗

优化后实现代码

import numpy as np

def find_peak_wing_nearest(peak_arr, target):
    # 定位全局峰值位置
    peak_idx = np.argmax(peak_arr)
    # 拆分两个单调半区,右半区反转后变为单调递增,适配二分查找要求
    left_half = peak_arr[:peak_idx+1]
    right_half_rev = peak_arr[peak_idx:][::-1]

    # 左半区查找最近值
    left_insert_pos = np.searchsorted(left_half, target)
    if left_insert_pos == 0:
        left_res = left_half[0]
    elif left_insert_pos == len(left_half):
        left_res = left_half[-1]
    else:
        # 对比插入点前后的候选值,选离目标更近的
        left_res = left_half[left_insert_pos] if abs(left_half[left_insert_pos] - target) < abs(left_half[left_insert_pos-1] - target) else left_half[left_insert_pos-1]

    # 右半区查找最近值
    right_insert_pos = np.searchsorted(right_half_rev, target)
    if right_insert_pos == 0:
        right_res = right_half_rev[0]
    elif right_insert_pos == len(right_half_rev):
        right_res = right_half_rev[-1]
    else:
        right_res = right_half_rev[right_insert_pos] if abs(right_half_rev[right_insert_pos] - target) < abs(right_half_rev[right_insert_pos-1] - target) else right_half_rev[right_insert_pos-1]
    
    return left_res, right_res

效果验证

测试用单峰数组:alt = np.array([120, 480, 2600, 4100, 3675, 1900, 220]),查找目标值1000的双侧匹配值,函数返回结果为(2600, 3675),完全匹配需求。

补充说明

  • 原尝试代码中的a= np.where(min(alt)==alt))存在两处可优化的点:存在冗余右括号,且逻辑是查找最小值而非峰值(单峰峰值为全局最大值),实际运行会出现半区切分错误,优化后的代码直接修正了该逻辑
  • 函数自带边界防护:当目标值大于/小于整个数组的所有值时,会自动取对应半区的边界值,不会触发索引越界报错
  • 右半区的反转操作是numpy的视图级操作,不会产生额外的内存拷贝开销,几乎不占用运行时间

内容的提问来源于stack exchange,提问作者Pavan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.29 00:36:04