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) 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值