import java.util.*;
public class TestHeapSorted {
public static void main(String[] args) {
Map<String, String> testMap = new HashMap<String, String>();
testMap.put("tag2", "2");
testMap.put("tag1", "1");
testMap.put("tag3", "3");
testMap.put("tag5", "5");
testMap.put("tag4", "4");
testMap.put("tag7", "7");
testMap.put("tag9", "9");
testMap.put("tag8", "8");
testMap.put("tag6", "6");
Object[] testObjectValue = testMap.values().toArray();
TestHeapSorted testHeapSorted = new TestHeapSorted();
System.out.println(testHeapSorted.GetLeastNumbers_Solution(testObjectValue, (3 + 1)));
List<Double> testList = testHeapSorted.GetLeastNumbers_Solution(testObjectValue, (3 + 1));
Iterator<Map.Entry<String, String>> it = testMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> entry = it.next();
for (int i = 0; i < testList.size(); i++) {
if (Double.parseDouble(entry.getValue()) == testList.get(i)) {
testList.remove(i);
it.remove();
break;
}
}
}
for (String key : testMap.keySet()) {
System.out.println(key + "=>" + testMap.get(key));
}
System.out.println(testList.size());
}
public ArrayList<Double> GetLeastNumbers_Solution(Object[] input, int k) {
ArrayList<Double> res = new ArrayList<Double>();
if (input == null || input.length == 0 || input.length < k) {
return res;
}
if (k == 0)
return res;
double[] maxHeap = new double[k];
//初始化堆
for (int i = 0; i < maxHeap.length; i++) {
maxHeap[i] = Double.parseDouble(input[i].toString());
}
//将初始化的堆调整为最大堆。最大堆:根节点的值总是大于子树中任意节点的值
// 注意是--i,从下往上
for (int i = (maxHeap.length - 1) / 2; i >= 0; i--) {
adjustHeap(maxHeap, i);
}
//遍历初始数组不断调整最大堆
for (int i = k; i < input.length; i++) {
if (maxHeap[0] > Double.parseDouble(input[i].toString())) {
maxHeap[0] = Double.parseDouble(input[i].toString());
adjustHeap(maxHeap, 0); // 是0位置,即根节点的值为最大值
}
}
for (int i = 0; i < maxHeap.length; i++) {
res.add(maxHeap[i]);
}
return res;
}
static void adjustHeap(double maxHeap[], int i) {
int index = i;
int lchild = 2 * i + 1; //i的左孩子节点序号
int rchild = 2 * i + 2; //i的右孩子节点序号
if (index <= (maxHeap.length - 1) / 2) {
//寻找子节点中最大的节点
if (lchild < maxHeap.length && maxHeap[index] < maxHeap[lchild]) { //左孩子大于index
index = lchild;
}
if (rchild < maxHeap.length && maxHeap[index] < maxHeap[rchild]) { //右孩子大于index
index = rchild; //此时index为左右孩子中较大的那个
}
if (i != index) {
//将节点与最大的子节点交换
double tmp = maxHeap[index];
maxHeap[index] = maxHeap[i];
maxHeap[i] = tmp;
//交换后,子树可能不满足最大推,递归调整。
adjustHeap(maxHeap, index); //因为交换下来一个小的数字,要调整的是被交换的子树
}
}
}
}
答案:
[4.0, 3.0, 2.0, 1.0]
tag5=>5
tag8=>8
tag9=>9
tag6=>6
tag7=>7
0