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.
上面的就是原题:
解答一:
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)
相关文章推荐
- Python笔试题目:求最大的K个数子,解法二,适合小型数据集的情况
- Python笔试题目:求最大的K个数子,解法三,适合大型数据集的情况
- 最大子段和解法及python实现
- Python实现快速多线程ping的方法
- 【程序员笔试面试必会——排序①】Python实现 冒泡排序、选择排序、插入排序、归并排序、快速排序、堆排序、希尔排序
- python通过shutil实现快速文件复制的方法
- python快速建立超简单的web服务器的实现方法
- python使用分治法实现求解最大值的方法
- python3实现最大子序列和的在线处理方法
- 使用Python求解最大公约数的实现方法
- Python实现快速多线程ping的方法
- 用三种方法实现最大子列和的求解(Python实现)
- Python cookbook(数据结构与算法)找到最大或最小的N个元素实现方法示例
- Python多种方法实现句子中单词倒置(好未来2017笔试题)
- 求两个数字的最大公约数-Python实现,三种方法效率比较,包含质数打印质数的方法
- 使用Python求解最大公约数的实现方法
- python使用分治法实现求解最大值的方法
- Python最大堆排序实现方法
- Python基于更相减损术实现求解最大公约数的方法
- python通过shutil实现快速文件复制的方法