Skip to content

Latest commit

 

History

History
34 lines (31 loc) · 1.2 KB

最小k个数.org

File metadata and controls

34 lines (31 loc) · 1.2 KB

题目

Screen-Pictures/%E9%A2%98%E7%9B%AE/2020-06-11_15-06-27_%E6%88%AA%E5%B1%8F2020-06-11%20%E4%B8%8B%E5%8D%883.06.24.png

思路

堆排序后取前k个值

code

#堆排序
        def build_heap(arr, root, end):
            while 1:
                child = 2*root+1
                if child > end:
                    break
                if child+1 <= end and arr[child+1] > arr[child]:
                    child += 1
                if arr[root] < arr[child]:
                    arr[root], arr[child] = arr[child], arr[root]
                    root = child
                else:
                    break

        def heap_sort(arr):
            n = len(arr)
            first_root = n//2 -1
            for root in range(first_root, -1, -1):
                build_heap(arr, root, len(arr)-1)
            for end in range(len(arr)-1, 0, -1):
                arr[0], arr[end] = arr[end], arr[0]
                build_heap(arr, 0, end-1)

        heap_sort(arr)
        return arr[:k]