剑指offer(29)最小的k个数
public class Solution {
public int[] GetLeastNumbers_Solution(int [] arr, int k) {
if(k < 1 || k > arr.length){
return arr;
}
int[] kHeap = new int[k];
for(int i = 0;i != k;i++){
heapInsert(kHeap, arr[i], i);
}
for(int i = k;i !=arr.length;i++){
if(arr[i] < kHeap[0]){
kHeap[0] = arr[i];
heapify(kHeap, 0 ,k);
}
}
return kHeap;
}
public void heapInsert(int[] arr,int value,int index){//建堆(大顶堆),向上建立的过程
arr[index] = value;
while(index != 0){
int parent = (index - 1)/2;
if(arr[parent] < arr[index]){
swap(arr, parent, index);
index = parent;
}else{
break;
}
}
}
public void heapify(int[] arr, int index, int heapSize){//调整堆的过程(向下调整)
int left = index * 2 + 1;
int right = index * 2 + 2;
int largest = index;
while(left < heapSize){
if(arr[left] > arr[index]){
largest = left;
}
if(right < heapSize && arr[right] > arr[largest]){
largest = right;
}
if(largest != index){
swap(arr, largest, index);
}else{
break;
}
index = largest;
left = index * 2 + 1;
right = index * 2 + 2;
}
}
public void swap(int[] arr , int index1 , int index2){
int temp = arr[index1];
arr[index1] = arr[index2];
arr[index2] = temp;
}
}
剑指offer上通过的用优先队列实现的版本:
import java.util.ArrayList;
import java.util.Queue;
import java.util.PriorityQueue;
import java.util.Comparator;
public class Solution {
public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
ArrayList<Integer> list = new ArrayList<Integer>();
if(input.length < k || k <= 0){
return list;
}
Queue<Integer> maxHeap = new PriorityQueue<Integer>(k, new Comparator<Integer>(){
@Override
public int compare(Integer o1, Integer o2){
return o2 - o1;
}
});
for(int i = 0;i <input.length;i++){
if(maxHeap.size() < k){
maxHeap.offer(input[i]);
}else if(input[i] < maxHeap.peek()){
maxHeap.poll();
maxHeap.offer(input[i]);
}
}
for(Integer integer : maxHeap){
list.add(integer);
}
return list;
}
}