输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
解题思路:方法一可以用类似patition的过程找到前k小的数,O(n)
还可以用最小堆来实现,O(nlogk)
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
ArrayList<Integer> res = new ArrayList<Integer>();
if(input == null || input.length <= 0 || k <= 0 || k > input.length) return res;
int low = 0;
int high = input.length-1;
int index = Patition(input, k, 0, input.length-1);
while(index != k-1){
if(index > k-1){
index = Patition(input, k, low, index-1);
}else{
index = Patition(input, k, index+1, high);
}
}
for(int i = 0; i < k; i++){
res.add(input[i]);
}
return res;
}
public int Patition(int[] input, int k, int low, int high){
int pivot = input[k-1];
swap(input, low, k-1);
while(low < high){
while(low < high && pivot <= input[high]){
high--;
}
swap(input, low, high);
while(low < high && pivot >= input[low]){
low++;
}
swap(input, low, high);
}
return low;
}
public void swap(int[] input, int i, int j){
int tmp = input[i];
input[i] = input[j];
input[j] = tmp;
}
}
下面堆的实现做法来自牛客网。
import java.util.ArrayList;
import java.util.PriorityQueue;
import java.util.Comparator;
public class Solution {
public ArrayList<Integer> GetLeastNumbers_Solution(int[] input, int k) {
ArrayList<Integer> result = new ArrayList<Integer>();
int length = input.length;
if(k > length || k == 0){
return result;
}
PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(k, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2.compareTo(o1);
}
});
for (int i = 0; i < length; i++) {
if (maxHeap.size() != k) {
maxHeap.offer(input[i]);
} else if (maxHeap.peek() > input[i]) {
Integer temp = maxHeap.poll();
temp = null;
maxHeap.offer(input[i]);
}
}
for (Integer integer : maxHeap) {
result.add(integer);
}
return result;
}
}