import java.util.HashMap;
//出現次數top K的進階問題
public class TopKAdvanceProblem{
//堆節點定義
public static class Node {
public String str;
public int times;
public Node(String s, int t) {
str = s;
times = t;
}
}
//TopK的記錄
public static class TopKRecord {
private Node[] heap;
private int index;
private HashMap<String, Node> strNodeMap;
private HashMap<Node, Integer> nodeIndexMap;
public TopKRecord(int size) {
heap = new Node[size];
index = ;
strNodeMap = new HashMap<String, Node>();
nodeIndexMap = new HashMap<Node, Integer>();
}
public void add(String str) {
Node curNode = null;
int preIndex = -;
if (!strNodeMap.containsKey(str)) {
curNode = new Node(str, );
strNodeMap.put(str, curNode);
nodeIndexMap.put(curNode, -);
} else {
curNode = strNodeMap.get(str);
curNode.times++;
preIndex = nodeIndexMap.get(curNode);
}
if (preIndex == -) {
if (index == heap.length) {
if (heap[].times < curNode.times) {
nodeIndexMap.put(heap[], -);
nodeIndexMap.put(curNode, );
heap[] = curNode;
heapify(, index);
}
} else {
nodeIndexMap.put(curNode, index);
heap[index] = curNode;
heapInsert(index++);
}
} else {
heapify(preIndex, index);
}
}
//獲得top k的數
public void printTopK() {
System.out.println("TOP: ");
for (int i = ; i != heap.length; i++) {
if (heap[i] == null) {
break;
}
System.out.print("Str: " + heap[i].str);
System.out.println(" Times: " + heap[i].times);
}
}
//向堆中添加資料
private void heapInsert(int index) {
while (index != ) {
int parent = (index - ) / ;
if (heap[index].times < heap[parent].times) {
swap(parent, index);
index = parent;
} else {
break;
}
}
}
//堆調整
private void heapify(int index, int heapSize) {
int l = index * + ;
int r = index * + ;
int smallest = index;
while (l < heapSize) {
if (heap[l].times < heap[index].times) {
smallest = l;
}
if (r < heapSize && heap[r].times < heap[smallest].times) {
smallest = r;
}
if (smallest != index) {
swap(smallest, index);
} else {
break;
}
index = smallest;
l = index * + ;
r = index * + ;
}
}
private void swap(int index1, int index2) {
nodeIndexMap.put(heap[index1], index2);
nodeIndexMap.put(heap[index2], index1);
Node tmp = heap[index1];
heap[index1] = heap[index2];
heap[index2] = tmp;
}
}
//獲得随機大小的數組
public static String[] generateRandomArray(int len, int max) {
String[] res = new String[len];
for (int i = ; i != len; i++) {
res[i] = String.valueOf((int) (Math.random() * (max + )));
}
return res;
}
//列印數組
public static void printArray(String[] arr) {
for (int i = ; i != arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
public static void main(String[]args){
TopKRecord record = new TopKRecord();
record.add("zuo");
record.printTopK(); //列印 topk
record.add("chao");
record.add("chao");
record.add("chao");
record.printTopK(); //列印 topk
record.add("ren");
record.add("ren");
record.printTopK();//列印 topk
}
}