设置大小为K的大根堆,当堆外元素小于堆顶,将其置换更新。到最后堆中元素,即为所求。
import java.util.ArrayList;
public class Solution {
int heap[];
int n;
public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
ArrayList<Integer>list=new ArrayList<Integer>();
int l=input.length;
if(l<k||k<1)
return list;
heap= new int [k+1];
n=0;//
for(int i=0;i<k;i++){
insert(input[i]);
}
for(int i=k;i<l;i++){
int m=getTop();
if(m>input[i]){
swap(input[i]);
}
}
for(int i=1;i<=n;i++){
list.add(heap[i]);
}
return list;
}
void up(int p){
while(p>1){
if(heap[p]>heap[p/2]){
int x=heap[p];
heap[p]=heap[p/2];
heap[p/2]=x;
p=p/2;
}
else{
break;
}
}
}
void insert(int val){
heap[++n]=val;
up(n);
}
int getTop(){
return heap[1];
}
void down(int p){
int s=p+p;
while(s<=n){
if(s<n&&heap[s]<heap[s+1]){
s++;
}
if(heap[s]>heap[p]){
int x=heap[p];
heap[p]=heap[s];
heap[s]=x;
p=s;
s=p+p;
}
else break;
}
}
void swap(int val){
heap[1]=val;
down(1);
}
}