在输入处给一个正整数N,并创建一个数组'A',其中每个元素从1到N的差为1。
A = [1,2,3,...,N]
我写了一段代码,随机生成1到N之间的整数的搜索值,并找到不超过搜索值但是最接近值的数组A的元素。
对于特定算法的应用,为了测量减震器的精度,假定进行了测试以检查不会破坏生鸡蛋的极限高度。 最大高度为N米,并且在可用于测试的生鸡蛋数量有限的情况下,搜索数量也会受到限制。
对于以下搜索次数不受限制的程序,计算复杂度为O(logN),但是对于搜索次数有限的第2号程序,无论速度如何,O(N)都是最快的。
如果2号程序的搜索次数有限,请告诉我是否还有另一种算法可以使计算量更快。
import random
# It is assumed that life-1 times can be exceeded in the search for the value you are looking for
def solution (N, d, l):
A = []
for i in range (1, N + 1, 1):
A.append (i)
target = random.randint (1, N)
life = l
#denominator
denominator = d
# Candidate molecule
numerator = []
for j in range (1, N-1, 1):
numerator.append (j)
# Set the value of the smallest position of the specified number of divisions to hi
1/3 if # k = 3, 1/6 if K = 6
lo = 0
hi = len (A) * (numerator [0] / denominator)
A variable that records the element number immediately before #life becomes 1
r = 0
for x in range (1, len (numerator), 1):
if life> 1:
if A [hi]> = target:
life = life-1:
r = hi
else:
hi = len (A) * (numerator [x] / denominator)
Linear search up to just before life becomes 1 when #life becomes 1
S = []
for t in range (r):
S.append (t)
# Difference between elements in array and target, tentatively assume initial value 100
diff = 100
The interval before # life becomes 1
for u in range (len (S)):
if target> S [u] and abs (target-S [u]) <diff:
place = u
return "Position" + str (place) + "Presence"
我想知道在可用鸡蛋数量有限的情况下找到极限高度比O(N)更快的算法。