繁体   English   中英

给定一个随机顺序的数字列表,编写一个算法,该算法在 O(nlog(n)) 中工作以找到列表中第 k 个最小的数字

[英]Given a list of numbers in random order, write an algorithm that works in O(nlog(n)) to find the kth smallest number in the list

我已经写了这个算法,但我不确定这是否正确,请帮助我解决这个问题,我是 Python 编程语言的初学者。

for n in maxN:
     alist = range(n)
     adict = {}
     for j in xrange(n):
         adict[j] = None
     random_index = random.randint(0, n-1)

     start1 = time.time()
     del_in_list(alist, random_index)
     end1 = time.time()

     start2 = time.time()
     del_in_dict(adict, random_index)
     end2 = time.time()

     start3 = time.time()
     empty(adict, random_index)
     end3 = time.time()

     y1.append(end1-start1-(end3-start3))
     y2.append(end2-start2-(end3-start3))    
 plt.plot(maxN,y1, "r--", maxN, y2)

plt.show()

如果是,此算法是否正确,那么如何线性改进此算法?

实际上有一种算法可以在线性时间内找到未排序列表中的第 K 个最小/最大元素。
为了以 O(n*log(n)) 的复杂度完成它,您所要做的就是对列表进行排序,然后检索第 n 个元素。 就像是 :

x = sorted(your_list)
print x[n]

如果您不希望第一个元素位于位置 0,只需将 n 更改为 n-1。

线性算法的解决方案可能是这样的(做一些改变)

import random

#creating random list
l =list(range(1000))
random.shuffle(l)

a=min(l)
b=max(l)

ch = [0 for i in range(a,b)]

i=a
while i<=b:
    pos = l[i] - a
    ch[pos] = ch[pos] + 1
    i += 1
sum=0
pos = 0
k = int(input("enter the value of kth element to find"))
while sum<k:
    sum = ch[pos] + sum
    pos = pos +1

x= ch[pos-1] + a
print("%d is the K'th element of the list" % (x))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM