select largest K number from unsorted array Python
来源:互联网 发布:烹尸奇案 知乎 编辑:程序博客网 时间:2024/04/29 10:49
heap:
take klog(n) time
code is as follow"
def siftdown(A, start, end):root = startchild = 2 * root + 1while child <= end:if child + 1 <= end and A[child] < A[child + 1]:child += 1if A[root] < A[child]:A[child], A[root] = A[root], A[child]root = childelse:returndef heapify(A, count):start = (count - 2) / 2while start >= 0:siftdown(A, start, count - 1)start = start -1#def heapsort(A):#count = len(A)#heapify(A, len(A))#end = count - 1#while end > 0:#A[end], A[0] = A[0], A[end]#end -= 1#siftdown(A, 0, end)#return Adef topk(A, k):count = len(A)heapify(A, len(A))end = len(A) - 1while end > 0 and k > 0:A[end], A[0] = A[0], A[end]end -= 1k -= 1siftdown(A, 0, end)return A[end + s1:] #def drawmax(A):A = [3, 4, 5, 1, 2, 0]print topk(A, 3)
quick select take O(n) time find k values
import randomdef partition(num, pivotIndex, left, right):pivot = num[pivotIndex]num[pivotIndex], num[right] = num[right], num[pivotIndex]storeIndex = leftfor i in range(left, right):if num[i]< pivot:num[storeIndex], num[i] = num[i], num[storeIndex]storeIndex += 1num[storeIndex], num[right] = num[right], num[storeIndex]return storeIndexdef quickselect(num, k):left = 0right = len(num) - 1while True:pivotIndex = random.randint(left,right)pivotNewIndex = partition(num, pivotIndex,left, right)dist = pivotNewIndex - leftif dist == k:return num[pivotNewIndex]elif dist > k:right = pivotNewIndex - 1else:k -= (dist+1)left = pivotNewIndex + 1 num =[8, 9,0,1,2,3,6,7]print quickselect(num,3)
0 0
- select largest K number from unsorted array Python
- Find the smallest positive number missing from an unsorted array
- good article————K’th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time)
- Find the kth largest element in an unsorted array
- the kth largest element in an unsorted array.
- Find the k-th minimal element of an unsorted array
- Get nth Max number in an array of unsorted integers.
- LintCode Kth Smallest Number in A Unsorted Array
- find kth largest number in an array
- [Leetcode] 179. Largest Number @python
- Multi select elements which sums upto a certain number from an array
- Multi select elements which sums upto a certain number from an array(II)
- CareerCup Find top k values (asec) which can either be the number from the array A
- The K-th largest number(小根堆)
- Contest6 The K-th largest number
- LeetCode--Largest Number(最大数字)Python
- Largest Number
- Largest Number
- 排序算法——冒泡排序
- DC DC同步降压芯片 DC-DC降压IC
- Find Minimum in Rotated Sorted Array
- Java多线程产生死锁的条件以及解决方法
- 设计模式:创建型模式:工厂模式(factory pattern)
- select largest K number from unsorted array Python
- ios iphone app界面设计尺寸规范
- Best way to learn android and java?
- I want to learn Android Development, where do I start?
- Coldfusion: 给CFML加上Wait功能(二)
- 细说Form表单
- Binary Tree Inorder Traversal
- Coldfusion: 给CFML加上Wait功能(三)
- 如何查询别人的微信聊天记录,如何查开房记录信息,怎么查通话记录,如何查询手机短信内容,如何查开房记录.qq:2540400410