《剑指Offer》刷题笔记——面试题40. 最小的k个数

难度:简单

一、题目描述:

在这里插入图片描述

二、解题分析:

class Solution:
    def getLeastNumbers(self, arr: List[int], k: int) -> List[int]:
        """快排partition划分"""      
        if len(arr) < k or k <= 0: return []
        low, high = 0, len(arr)-1
        idx = self.partition(arr, low, high)
        while idx != k-1:
            if idx < k-1:
                low = idx + 1
                idx = self.partition(arr, low, high)
            if k-1 < idx:
                high = idx - 1
                idx = self.partition(arr, low, high)
        return arr[:k]

    def partition(self, nums, low, high):
        pivot = nums[low]
        while low < high:
            while low < high and pivot <= nums[high]:
                high -= 1 
            nums[low] = nums[high]
            while low < high and nums[low] <= pivot:
                low += 1
            nums[high] = nums[low]
        nums[low] = pivot
        return low

        # arr.sort()
        # return arr[:k]
class Solution:
    def getLeastNumbers(self, arr: List[int], k: int) -> List[int]:
        arr.sort()
        return arr[:k]
发布了133 篇原创文章 · 获赞 155 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_34108714/article/details/104693740
今日推荐