Python筆試題目:求最大的K個數子,解法一,最快速實現的方法

題目:

Givena array of 10,000 random intergers, select the biggest 100 numbers.

1)The order of the result numbers does not matter;

2)Take care about the algorithm performance and big O complexity.


上面的就是原題:

解答一:

#coding=utf-8
 
 
## generate random numbers
from random import randint
# low and high limit of the numbers of the random number
low = -10000000
high = 10000000
 
# total_number of the numbers
total_number = 10000
# the number of beggest number we need
max_number = 100
 
# use  () for [] will be more efficient ?   
numbers = [randint(low,high) for elem in xrange(total_number)]
#print numbers
 
 
## method one 
## sort and select using the built-in sort() function of Python
## sort() vs sorted()
"""
complexity: N*log(N), due to merge sort and Timsort algorithm, need N extra space
advantage: quick to implementate
disadvantages:
(1)python's sort() function is Timsort algorithm, which finds subsets of the data that are already ordered, 
and uses that knowledge to sort the remainder more efficiently.
so, this algorithm is not the best of this scenarios random numbers.
(2)what's more, The order of the result numbers does not matter ;
(3)we don't need all the numbers sorted.
(4) merge sort algorithm need size N extra space , which is not suitable when the size is very large, 
remainds to do: sort() is sort inplace , sorted() not. sorted() consumes more space ,
                will sorte() be more efficient ,or out of place sort is just of a matter of usage?
"""
numbers.sort()
max_number_list = numbers[-max_number:]  # sort  vs  sorted ; and the algorithm behind ?sort
print 'the biggest %s numbers are: %s' %(max_number, max_number_list) 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章