最大堆求解K min值问题
最小的K个数
http://www.nowcoder.com/questionTerminal/6a296eb82cf844ca8539b57c23e6e9bf
import java.util.*;
public class Solution {
public void swap(int i,int j,int nums[]){
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
public void sift_down(int i,int nums[],int n){
while(i * 2 + 1 <= n){
if(i * 2 + 2 <= n && nums[i * 2 + 2] <= nums[i * 2 + 1]){
if(nums[i] > nums[i * 2 + 2]){
swap(i,i2+2,nums);
}
i = i * 2 + 2;
}
else{
if(nums[i] > nums[i * 2 + 1]){
swap(i,i2+1,nums);
}
i = i * 2 + 1;
}
}
}
public void create(int nums[]){
for(int i = nums.length / 2 - 1;i >= 0; i--){
sift_down(i,nums,nums.length - 1);
}
}
public ArrayList<integer> get_K_min(int nums[],int k){
ArrayList<integer> list = new ArrayList<integer>();
int n = nums.length - 1;
while(n >= 0){
list.add(nums[0]);
swap(0,n,nums);
n--;
k--;
sift_down(0,nums,n);
if(k == 0) break;
}
return list;
}
public ArrayList<integer> GetLeastNumbers_Solution(int [] input, int k) {
create(input);
if(k == 0) return new ArrayList<integer>();
if(k > input.length) return new ArrayList<integer>();
return get_K_min(input,k);
}
}</integer></integer></integer></integer></integer></integer>