LeetCode-Notes
  • Introduction
  • Records of Practice
  • 关于Github 不支持密码问题
  • 面试题
    • 搜索广告
    • 多模态大模型
    • 刷题记录
  • 算法代码实现
  • Python
    • Python 笔记
  • Spark
    • PySpark
    • Spark Issues
    • Spark调优笔记
  • FeatureEngineering
    • Feature Cleaning
    • Feature Selection
    • Feature Transformation
    • Feature Crossing
  • Recommendation Algorithm
    • Recall-and-PreRank
      • Non-Negative Matrix Fatorization(NMF)
      • Fatorization Machine(FM)
      • User-base/Item-base实现
      • 多路召回实现
    • Ranking
      • NeuralFM
      • DeepFM
      • Deep&Cross network (DCN)
    • DeepLearning-Basic
      • Attention
      • Dropout
      • Batch Norm
  • Machine Learning
    • XGBoost
    • Cross Entropy Loss
    • Other models
  • Graph Neural Network
    • GNN-1-Basic
  • Big Data
    • Reservoir Sampling
  • SQL
    • SQL and PySpark functions
    • Query Film Infomation
    • Create, Insert and Alter Actor Table
    • Manage Employment Data
    • Manage Employment Data -2
  • DataStructure
    • Searching
      • Find power
      • 2 Sum All Pair II
      • Two Sum
      • Search in Rotate Array
      • Search In Shifted Sorted Array II
      • Search in 2D array
      • Three Sum with duplicated values
      • Median of Two Sorted Arrays
    • Array
      • Longest Consecutive Subarray
      • Merge Two Array in-place
      • Trapping water
      • Rotate matrix
    • Sorting
      • Merge intervals
      • 排序
      • 最小的k个数
      • Find TopK largest- QuickSelect快速选择 method
      • MergeSort Linkedlist
      • 第K大元素
    • LinkedList
      • Reverse LinkedList I
      • Reverse K-group linked list
      • Detect Start of Cycle
      • HasCycle
      • DetectCycle II
      • 链表的共同节点
      • 链表中倒数第k个节点
      • 删除链表倒数第k个节点
      • 合并两个链表
      • 在排序数组中查找元素的第一个和最后一个位置
      • 删除链表里面重复的元素-1
    • Tree
      • Find Tree height (general iteration method)
      • Check BST and Check CompleteTree
      • ZigZag Order traversal
      • Binary Tree diameter I
      • Maximum Path Sum Binary Tree
      • Maximum Path Sum Binary Tree II
      • Binary Tree Path Sum To Target III
      • Tree diameter 树的直径II
      • Tree ReConstruction
      • Check if B is Subtree of A
      • The Kth smallest in Binary Search Tree
      • 打印Tree的右视图
      • 二叉搜索树的后序遍历序列
      • 重建二叉树
      • 判断二叉树是否对称
      • Path Sum to Target in Binary Tree
      • Tree-PreOrder-InOrder-PostOrder
    • Heap&Queue
      • Top-K smallest
      • 滑动窗口最大值
      • Find the K-Largest
    • 合并k个已排序的链表
    • String
      • Reverse String
      • 最长不含重复字符的子字符串
      • 最长回文串
      • 最长回文子序列-DP
    • DFS/BFS
      • Number of island
      • Number of Provinces
      • All Permutations of Subsets without duplication
      • All Permutations of Subsets with duplication
      • Combinations Of Coins
      • All Subset I (without fixing size of subset, without order, without duplication)
      • All Subset of K size without duplication II
      • All Subset of K size III (with duplication without considering order)
      • All Permutation II (with duplication and consider order)
      • Factor Combination-质数分解
    • DynamicProgramming
      • DP-解题过程
      • Find Continuous Sequence Sum to Target
      • 1800. Maximum Ascending Subarray Sum
      • NC91 最长上升子序列
      • 查找string的编码方式个数
      • Maximum Product
      • Longest Common Substring
      • Longest Common Substring-II
      • minEditCost
      • Backpack I
      • Array Hopper I
      • Minimum distance between strings
      • 最大正方形
  • Big Data Algorithms
    • Big Data Processing Algorithms
      • Reservior Sampling
      • Shuffle
      • MapReduce
      • Bloom Filter
      • BitMap
      • Heap For Big Data
Powered by GitBook
On this page
  • 0. Links
  • 1. 题目
  • 题目描述
  • 输入
  • 返回值
  • 2. 思路
  • 3.Coding

Was this helpful?

  1. DataStructure
  2. Heap&Queue

Top-K smallest

PreviousHeap&QueueNext滑动窗口最大值

Last updated 4 years ago

Was this helpful?

0. Links

牛客:

laicode K-largest:

1. 题目

题目描述

给定一个数组,找出其中最小的K个数。例如数组元素是4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4。如果K>数组的长度,那么返回一个空的数组示例1

输入

复制

[4,5,1,6,2,7,3,8],4

返回值

复制

[1,2,3,4]

2. 思路

a.方法1: heap,用max heap (min heap + 把value 取反reverse)思路

1. 先把前k个element build heap

2. 在剩下的element里面不断把element 取反并加入heap,heap每次把当前最小(取反最大)的数pop出去,剩下的heap里面的k element就是当前最大(加负号取反后最小的k个数)

3. Time: O(k) for popping top k elements to list, O(klogk) for build heap, O((n-k)logk) for updating heap, O(k) for reversing list and return result. So O(k+ nlogk)

4. Space: O(k) for heap

方法2:直接先通过min heap把整个list heapify,再pop到剩下k个element

Time: O(n +klogn) in total, O(n) for building heap, O(klogn) popping 最小的k个element

Space: O(n)

方法3: quickselect

3.Coding

import heapq
class Solution:
    def GetLeastNumbers_Solution(self, tinput, k):
        # write code here
        # base case: when k > tinput or k<1: return None
        # method 2 : max-heap with k element
        #   pop the top k element to heap and then heapify max heap with K element
        #    iterate the n-k element
        #        if element > the top element in heap / max element in heap, skip
        #           else: pop the max element and append current element
        #  Finally  we find the K smallest element in heap only
        # 
        # Time O(klogk) for heapify  + O((n-k)logk ) for popping and inserting element
        #  SO  O(nlogk) in total
#       #
        # Space:  O(k) for heap
        #
        #
        #
        if not tinput or (k > len(tinput) or k<1):
            return []
        #O(k)
        heap = []
        for i in range(k):
            heap.append(-tinput.pop())
        # O(klogk)
        heapq.heapify(heap)
        # O((n-k)logk)
        for i in range(len(tinput)):
            if -tinput[i] > heap[0]:
                heapq.heappop(heap)
                heapq.heappush(heap,-tinput[i])
        #O(klogk)
        res = []
        while len(heap):
            res.append(-heapq.heappop(heap))
        # O(n)
        res.reverse()
        return res
            

https://www.nowcoder.com/practice/6a296eb82cf844ca8539b57c23e6e9bf?tpId=188&tqId=38031&rp=1&ru=%2Factivity%2Foj&qru=%2Fta%2Fjob-code-high-week%2Fquestion-ranking&tab=answerKey
https://app.laicode.io/app/problem/436