剑指offer面试题40.最小的k个数

1.题目描述

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

来源:https://www.nowcoder.com/practice/6a296eb82cf844ca8539b57c23e6e9bf?tpId=13&tqId=11182&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

2.解题思路

方法一:快速排序,O(n),修改原数组

要注意和原始快排的区别, 当不满足start < end时,需要返回end,而不是直接返回

方法二:堆排序(k个元素的最大堆),O(nlogk),适合海量数据,如果待插入的值比当前已有的最大值小,则用这个数替换当前已有的最大值,如果待插入的值比当前已有的最大值大,那么这个数不可能是最小的整数之一

3.代码实现

方法一:

# -*- coding:utf-8 -*-
class Solution:
    def partition(self, start, end, nums):
        if start < end:
            i = start
            j = end + 1
            K = nums[start]
            while i < j:
                i += 1
                while i < end and nums[i] < K:
                    i += 1
                j -= 1
                while j > start and nums[j] > K:
                    j -= 1
                if i < j:
                    nums[i], nums[j] = nums[j], nums[i]
            nums[start], nums[j] = nums[j], nums[start]
            return j
        # 注意和原始快排的区别
        else:
            return end

    def GetLeastNumbers_Solution(self, tinput, k):
        # write code here
        if k == 0 or len(tinput) == 0:
            return []
        if k > len(tinput):
            return []
        start=0
        end=len(tinput)-1
        index = self.partition(start, end, tinput)
        while True:
            if index == k - 1:
                print tinput[:k]
                res=tinput[:k]
                res.sort()
                return res
            elif index < k - 1:
                start = index + 1
                index=self.partition(start, end, tinput)
            else:
                end = index - 1
                index=self.partition(start, end, tinput)

方法二:

import heapq
class Solution:
    def GetLeastNumbers_Solution(self, tinput, k):
        # write code here
        if k == 0 or len(tinput) == 0:
            return []
        if k > len(tinput):
            return []
        heap=[-tinput[i] for i in range(k)]
        heapq.heapify(heap)

        for i in range(k,len(tinput)):
            if tinput[i]<-heap[0]:
                heapq.heapreplace(heap,-tinput[i])
        heap = [-heap[i] for i in range(k)]
        heap.sort()
        return heap

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值