关于迭代器和n log n解决方案的一些问题

问题描述

我的代码描述如下:

我的问题:给定一个数字和另一个其他数字的序列,找到大于或等于该数字的最接近值的索引。 第一:我不知道什么数据结构适合这个。

第二:我的解决方案花费了 O(n^2) 时间复杂度,因为我认为我使用了花费 O(n) 时间的距离函数。但我不知道任何其他解决方案 O(nlogn)

from bs4 import BeautifulSoup
html = '<span class="New_Link" id="tid_5785847"><a href="showthread.PHP? 
tid=5785847">Some text here?</a></span>'

soup = BeautifulSoup(html,'html.parser')
span_attribute = soup.find('span')
id_value = span_attribute.get('id')  # it is your ID from id="tid_5785847"
id_value = id_value.replace('tid_','')  # replace tid_
print(id_value)  # print only 5785847

解决方法

我不确定,但对我来说这似乎是一个 O(n) 问题:

int best = INT_MAX;
int ibest = -1;
for (int i = 0; i < arr.size(); i++) { 
     if (val <= arr[i] && arr[i] < best) {
        best = arr[i];
        ibest = i;
   } 
}
,

您可以为此进行基本的二进制搜索,将数字按排序顺序存储在成对的向量中。 pair 的第一个值将是该值,第二个值将是该数字在 arr 中的索引。对 value 进行二分搜索,这将在 O(log(n)) 中完成任务。

,

但我认为插入已排序的数组将花费 O(n) 时间