设计一个算法,找出数组中最小的k个数。以任意顺序返回这k个数均可。
示例:
输入: arr = [1,3,5,7,2,4,6,8], k = 4 输出: [1,2,3,4]
提示:
0 <= len(arr) <= 100000
0 <= k <= min(100000, len(arr))
方法一:排序
直接排序,取前 k 个数即可。
时间复杂度
方法二:优先队列(大根堆)
维护一个大小为
遍历结束,将堆中元素的
时间复杂度
class Solution:
def smallestK(self, arr: List[int], k: int) -> List[int]:
return sorted(arr)[:k]
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]
class Solution {
public int[] smallestK(int[] arr, int k) {
Arrays.sort(arr);
int[] ans = new int[k];
for (int i = 0; i < k; ++i) {
ans[i] = arr[i];
}
return ans;
}
}
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;
}
}
class Solution {
public:
vector<int> smallestK(vector<int>& arr, int k) {
sort(arr.begin(), arr.end());
vector<int> ans(k);
for (int i = 0; i < k; ++i) {
ans[i] = arr[i];
}
return ans;
}
};
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;
}
};
func smallestK(arr []int, k int) []int {
sort.Ints(arr)
ans := make([]int, k)
for i, v := range arr[:k] {
ans[i] = v
}
return ans
}
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 interface{}) { h.IntSlice = append(h.IntSlice, v.(int)) }
func (h *hp) Pop() interface{} {
a := h.IntSlice
v := a[len(a)-1]
h.IntSlice = a[:len(a)-1]
return v
}