Skip to content

Commit 164ddad

Browse files
committed
feat: add python and java solutions to lcof problem
添加《剑指 Offer》题解:面试题40. 最小的k个数
1 parent 805cdee commit 164ddad

File tree

3 files changed

+103
-0
lines changed

3 files changed

+103
-0
lines changed
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
# [面试题40. 最小的k个数](https://leetcode-cn.com/problems/zui-xiao-de-kge-shu-lcof/)
2+
3+
## 题目描述
4+
输入整数数组 `arr`,找出其中最小的 `k` 个数。例如,输入 4、5、1、6、2、7、3、8 这 8 个数字,则最小的 4 个数字是 1、2、3、4。
5+
6+
**示例 1:**
7+
8+
```
9+
输入:arr = [3,2,1], k = 2
10+
输出:[1,2] 或者 [2,1]
11+
```
12+
13+
**示例 2:**
14+
15+
```
16+
输入:arr = [0,1,2,1], k = 1
17+
输出:[0]
18+
```
19+
20+
**限制:**
21+
22+
- `0 <= k <= arr.length <= 10000`
23+
- `0 <= arr[i] <= 10000`
24+
25+
## 解法
26+
### Python3
27+
```python
28+
import heapq
29+
30+
class Solution:
31+
def getLeastNumbers(self, arr: List[int], k: int) -> List[int]:
32+
if k == 0:
33+
return []
34+
heap = []
35+
for e in arr:
36+
heapq.heappush(heap, e)
37+
return heapq.nsmallest(k, heap)
38+
```
39+
40+
### Java
41+
```java
42+
class Solution {
43+
public int[] getLeastNumbers(int[] arr, int k) {
44+
if (k == 0) {
45+
return new int[]{};
46+
}
47+
PriorityQueue<Integer> bigRoot = new PriorityQueue<>(k, Collections.reverseOrder());
48+
for (int e : arr) {
49+
if (bigRoot.size() < k) {
50+
bigRoot.offer(e);
51+
} else {
52+
if (e < bigRoot.peek()) {
53+
bigRoot.poll();
54+
bigRoot.offer(e);
55+
}
56+
}
57+
}
58+
int[] res = new int[k];
59+
for (int i = 0; i < k; ++i) {
60+
res[i] = bigRoot.poll();
61+
}
62+
return res;
63+
}
64+
}
65+
```
66+
67+
### ...
68+
```
69+
70+
```
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
class Solution {
2+
public int[] getLeastNumbers(int[] arr, int k) {
3+
if (k == 0) {
4+
return new int[]{};
5+
}
6+
PriorityQueue<Integer> bigRoot = new PriorityQueue<>(k, Collections.reverseOrder());
7+
for (int e : arr) {
8+
if (bigRoot.size() < k) {
9+
bigRoot.offer(e);
10+
} else {
11+
if (e < bigRoot.peek()) {
12+
bigRoot.poll();
13+
bigRoot.offer(e);
14+
}
15+
}
16+
}
17+
int[] res = new int[k];
18+
for (int i = 0; i < k; ++i) {
19+
res[i] = bigRoot.poll();
20+
}
21+
return res;
22+
}
23+
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import heapq
2+
3+
class Solution:
4+
def getLeastNumbers(self, arr: List[int], k: int) -> List[int]:
5+
if k == 0:
6+
return []
7+
heap = []
8+
for e in arr:
9+
heapq.heappush(heap, e)
10+
return heapq.nsmallest(k, heap)

0 commit comments

Comments
 (0)