Update 40. 最小的 K 个数.md

题目链接改为力扣中的对应题目,题目描述和代码按该题的接口调整。
This commit is contained in:
CyC2018
2026-10-28 13:45:05 +08:00
parent 6378a85835
commit defc62df9c
+21 -16
View File
@@ -2,7 +2,7 @@
## 题目链接
[牛客网](https://www.nowcoder.com/practice/6a296eb82cf844ca8539b57c23e6e9bf?tpId=13&tqId=11182&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github)
[Leetcode](https://leetcode.cn/problems/zui-xiao-de-kge-shu-lcof/)
## 解题思路
@@ -18,16 +18,21 @@
Java 的 PriorityQueue 实现了堆的能力,PriorityQueue 默认是小顶堆,可以在初始化时使用 Lambda 表达式 (o1, o2) -\> o2 - o1 来实现大顶堆。其它语言也有类似的堆数据结构。
```java
public ArrayList<Integer> GetLeastNumbers_Solution(int[] nums, int k) {
if (k > nums.length || k <= 0)
return new ArrayList<>();
public int[] inventoryManagement(int[] stock, int cnt) {
if (cnt > stock.length || cnt <= 0)
return new int[0];
PriorityQueue<Integer> maxHeap = new PriorityQueue<>((o1, o2) -> o2 - o1);
for (int num : nums) {
for (int num : stock) {
maxHeap.add(num);
if (maxHeap.size() > k)
if (maxHeap.size() > cnt)
maxHeap.poll();
}
return new ArrayList<>(maxHeap);
int[] ret = new int[cnt];
int i = 0;
while (!maxHeap.isEmpty()) {
ret[i++] = maxHeap.poll();
}
return ret;
}
```
@@ -39,18 +44,18 @@ public ArrayList<Integer> GetLeastNumbers_Solution(int[] nums, int k) {
快速排序的 partition() 方法,会返回一个整数 j 使得 a[l..j-1] 小于等于 a[j],且 a[j+1..h] 大于等于 a[j],此时 a[j] 就是数组中第 j 小的元素(j 从 0 开始计数)。可以利用这个特性找出数组的第 K 个元素,这种找第 K 个元素的算法称为快速选择算法。
```java
public ArrayList<Integer> GetLeastNumbers_Solution(int[] nums, int k) {
ArrayList<Integer> ret = new ArrayList<>();
if (k > nums.length || k <= 0)
return ret;
findKthSmallest(nums, k - 1);
/* findKthSmallest 会改变数组,使得前 k 个数都是最小的 k 个数 */
for (int i = 0; i < k; i++)
ret.add(nums[i]);
public int[] inventoryManagement(int[] stock, int cnt) {
if (cnt > stock.length || cnt <= 0)
return new int[0];
findKthSmallest(stock, cnt - 1);
/* findKthSmallest 会改变数组,使得前 cnt 个数都是最小的 cnt 个数 */
int[] ret = new int[cnt];
for (int i = 0; i < cnt; i++)
ret[i] = stock[i];
return ret;
}
public void findKthSmallest(int[] nums, int k) {
private void findKthSmallest(int[] nums, int k) {
int l = 0, h = nums.length - 1;
while (l < h) {
int j = partition(nums, l, h);