【问题标题】:Multiple Binary Search in Array/List数组/列表中的多重二分查找
【发布时间】:2020-12-04 22:42:08
【问题描述】:

这是执行二分查找的常用程序

def binary_search(lst,num):
    fl=0
    low=0
    high=len(lst)
    while low<=high :
        mid=int((low+high)/2)
        if lst[mid]==num :
            fl=1
            print ('Number Found at index:',mid)
            break
        elif lst[mid]>num :
            low=mid+1
        else :
            high=mid-1
    if fl==0 :
        print ('Number Not Found')
lst=eval(input("Enter a sorted list:")
num=int(input("Enter a number to find:")
binary_search(lst,num)

问题
如果我想搜索和打印元素的索引,如果它在列表/数组中出现超过 1 次,我该怎么办
示例: List= [1,1,1, 2,3,4,5]
我想搜索 1 并且它存在 3 次,所以我想打印所有 3 个索引,例如:-

在索引处找到的数字:0
在索引处找到的数字:1
在索引处找到的数字:2

(必须进行二进制搜索)

【问题讨论】:

  • 您可以采用两种方法:(1) 找到一个元素后,您可以前后扫描以找到第一个和最后一个,或者 (2) 您可以进行两次二进制搜索,一个它找到第一个实例,一个找到最后一个实例。哪个更快取决于您期望的重复次数。

标签: python python-3.x loops arraylist binary-search


【解决方案1】:

这段代码应该满足你的要求:

def binary_search(lst, num):
    element_found = False
    low = 0
    high = len(lst)
    while low <= high:
        mid = (low + high) // 2
        if lst[mid] == num:
            # Here you have found your element. If the list has several times this values, it will be the neighbours
            element_found = True
            find_equal_neighbours(lst, mid)
            break
        elif lst[mid] < num:
            low = mid + 1
        else:
            high = mid - 1
    if not element_found:
        print('Number Not Found')


def find_equal_neighbours(lst, index):
    low_index = index
    high_index = index
    value = lst[index]
    while low_index - 1 >= 0 and lst[low_index - 1] == value:
        low_index -= 1
    while high_index + 1 < len(lst) and lst[high_index + 1] == value:
        high_index += 1
    for i in range(low_index, high_index + 1):
        print('Number Found at index:', i)


lst = [1, 1, 1, 3, 4, 5]
num = 1
binary_search(lst, num)

一旦你通过二分搜索找到了你想要的元素,如果列表中还有其他具有相同值的元素,它们将在你的元素旁边(因为这是一个排序列表)。 函数find_equal_neigbours(lst, index) 打印与列表lst 中索引index 处的元素相等的所有neigbhours 值的索引。

打印出来:

Number Found at index: 0
Number Found at index: 1
Number Found at index: 2

【讨论】:

  • 这是我描述的两种方法中的第一种。如果没有太多重复,它会很好地工作,但在最坏的情况下(即所有元素都相同)它是 O(n)。另一种解决方案是在最坏的情况下为 O(log(n)),但在只有几个重复项时会更慢。
猜你喜欢
  • 1970-01-01
  • 2010-09-19
  • 1970-01-01
  • 1970-01-01
  • 2023-03-12
相关资源
最近更新 更多