您的位置:首页 > 编程语言 > Python开发

Python笔试题目:求最大的K个数子,解法一,最快速实现的方法

2014-10-13 21:45 323 查看
题目:

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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: