最小的k个数(最大堆,海量数据)

题目描述

输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。

思路:维护一个大小为k的最大堆,先初始化前k个数,然后滑动窗口,如果比堆顶大,直接抛弃,比堆顶小交换再调整堆。

# -*- coding:utf-8 -*-
class Solution:
    def GetLeastNumbers_Solution(self, tinput, k):
        # write code here
        heap = self.Build_Heap(tinput[:k])
        for i in range(k, len(tinput)):
            if tinput[i] >= heap[0]:
                continue
            else:
                heap[0] = tinput[i]
                for i in range(k-1,-1,-1):
                    self.Adjust_Heap(heap, 0, k)
        print heap
        return heap
        
    def Adjust_Heap(self, tinput, root, heap_size):
        left = 2*root+1
        right = left + 1
        larger = root
        if left < heap_size and tinput[left] > tinput[root]:
            larger = left
        if right < heap_size and tinput[right] > tinput[root]:
            larger = right
        if larger != root:
            tinput[root], tinput[larger] = tinput[larger], tinput[root]
            self.Adjust_Heap(tinput, larger, heap_size)
 
    def Build_Heap(self, heap):
        HeapSize = len(heap)
        for i in range((HeapSize-1)//2, -1, -1):
            self.Adjust_Heap(heap,i, HeapSize)
        return heap
 
s = [4,5,1,6,2,7,3,8,435,32,13,5,2,99,0,-67,-7,56,35,637,73,2]
m = Solution()
m.GetLeastNumbers_Solution(s, 8)

猜你喜欢

转载自blog.csdn.net/qq_32445015/article/details/102083033