Description
Design an algorithm to find the smallest K numbers in an array.
Example:
Input: arr = [1,3,5,7,2,4,6,8], k = 4
Output: [1,2,3,4]
Note:
0 <= len(arr) <= 100000
0 <= k <= min(100000, len(arr))
Solutions
Solution 1
Solution 2
| class Solution:
def smallestK(self, arr: List[int], k: int) -> List[int]:
h = []
for v in arr:
heappush(h, -v)
if len(h) > k:
heappop(h)
return [-v for v in h]
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 | class Solution {
public int[] smallestK(int[] arr, int k) {
PriorityQueue<Integer> q = new PriorityQueue<>((a, b) -> b - a);
for (int v : arr) {
q.offer(v);
if (q.size() > k) {
q.poll();
}
}
int[] ans = new int[k];
int i = 0;
while (!q.isEmpty()) {
ans[i++] = q.poll();
}
return ans;
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 | class Solution {
public:
vector<int> smallestK(vector<int>& arr, int k) {
priority_queue<int> q;
for (int& v : arr) {
q.push(v);
if (q.size() > k) {
q.pop();
}
}
vector<int> ans;
while (q.size()) {
ans.push_back(q.top());
q.pop();
}
return ans;
}
};
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25 | func smallestK(arr []int, k int) []int {
q := hp{}
for _, v := range arr {
heap.Push(&q, v)
if q.Len() > k {
heap.Pop(&q)
}
}
ans := make([]int, k)
for i := range ans {
ans[i] = heap.Pop(&q).(int)
}
return ans
}
type hp struct{ sort.IntSlice }
func (h hp) Less(i, j int) bool { return h.IntSlice[i] > h.IntSlice[j] }
func (h *hp) Push(v any) { h.IntSlice = append(h.IntSlice, v.(int)) }
func (h *hp) Pop() any {
a := h.IntSlice
v := a[len(a)-1]
h.IntSlice = a[:len(a)-1]
return v
}
|