class Hoop {
int tree[];
int size;
public Hoop(int capacity) {
this.tree = new int[capacity + 1];
this.size = 1;
}
public void add(int val){
if (size == tree.length + 1) {
return;
}
tree[size] = val;
push(size);
size++;
}
public int poll() {
if (size < 1) {
size = 1;
return -1;
}
int t = tree[1];
tree[1] = tree[size - 1];
size--;
pop(1);
return t;
}
private void push(int index) {
if (index == 1){
return;
}
int father = index / 2;
if (tree[index] < tree[father]) {
int t = tree[index];
tree[index] = tree[father];
tree[father] = t;
push(father);
}
}
private void pop(int idx) {
if (idx >= tree.length) {
return;
}
int left = 2 * idx;
int right = 2 * idx + 1;
int leftVal = left >= size ? Integer.MAX_VALUE : tree[left];
int rightVal = right >= size ? Integer.MAX_VALUE : tree[right];
int min = Math.min(tree[idx], Math.min(leftVal, rightVal));
if (min == tree[idx]) {
return;
} else if (min == leftVal) {
int t = tree[idx];
tree[idx] = tree[left];
tree[left] = t;
pop(left);
} else {
int t = tree[idx];
tree[idx] = tree[right];
tree[right] = t;
pop(right);
}
}
public boolean isEmpty() {
return size == 1;
}
}
添加操作:将元素加到数组最后,从下往上与父亲节点找到对应位置
删除操作:将最后一个元素,替代根节点,然后从上往下比较自己与左右孩子组成的三元组,谁最小,直到自身为最小值,结束