解题思路:小根堆,每次从小根堆中取出最小的,并重新构建小跟堆,最后返回k个放集合里
import java.util.*;
public class Solution {
public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
if (input == null || input.length == 0 || k <= 0 || k > input.length) {
return new ArrayList<Integer>() ;
}
int size = input.length - k;
PriorityQueue<Integer> minQueue = new PriorityQueue<>((o1, o2)->o1 - o2);
int i = 0;
for (; i <= size; i++) {
minQueue.offer(input[i]);
}
ArrayList<Integer> list = new ArrayList<>();
list.add(minQueue.peek());
for (; i < input.length; i++) {
minQueue.poll();
minQueue.offer(input[i]);
list.add(minQueue.peek());
}
return list;
}
}
解法二:大根堆(存储k个元素),每次比较根与当前值的大小,当前值小先把跟移除,再把当前值放到根里,重新维护这个大根堆。
import java.util.*;
public class Solution {
public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
if (input == null || input.length == 0 || k <= 0 || k > input.length) {
return new ArrayList<Integer>() ;
}
PriorityQueue<Integer> queue = new PriorityQueue<>((o1, o2)->o2 - o1);
ArrayList<Integer> list = new ArrayList<>();
int i = 0;
for (; i < k; i++) {
queue.offer(input[i]);
}
for (; i < input.length; i++) {
if (input[i] < queue.peek()) {
queue.poll();
queue.offer(input[i]);
}
}
while (!queue.isEmpty()) {
list.add(queue.poll());
}
return list;
}
}
方法三:使用系统自带的排序
import java.util.*;
public class Solution {
public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
if (input == null || input.length == 0 || k <= 0 || k > input.length) {
return new ArrayList<Integer>() ;
}
ArrayList<Integer> list = new ArrayList<>();
Arrays.sort(input);
for (int i = 0; i < k; i++) {
list.add(input[i]);
}
return list;
}
}