目前在学习算法,在这里记录下自己手写实现堆的过程
class Solution {
class MyHeap {
// 堆的最大长度
int maxLength = 0;
// 用数组存储的堆
int[] heap;
// 堆中当前元素的长度
int index = 0;
// 构造函数,构造当前的堆,参数为堆的最大长度
public MyHeap(int maxLength) {
this.maxLength = maxLength;
this.heap = new int[maxLength];
}
// 获取堆当前的长度
public int size() {
return this.index;
}
// 插入元素时构建堆
public void add(int n) {
// 将添加的元素加入到堆底
heap[index] = n;
// 不断向上调整
heapInsert(index);
index++;
}
//向上调整堆
private void heapInsert(int index) {
// 不断将节点与父节点进行比较,如果比父节点大,父节点和子节点交换位置
while ((index - 1) / 2 >= 0 && heap[(index - 1) / 2] < heap[index]) {
swap(index, (index - 1) / 2);
index = (index - 1) / 2;
}
}
// 弹出堆顶的元素,继续调整堆
public int pop() {
// 获取堆顶元素返回
int ans = heap[0];
// 将堆底元素交换到堆顶
swap(0, index - 1);
// 堆的长度减一
index--;
// 从堆顶开始向下调整
heapify(0);
return ans;
}
private void heapify(int index) {
int left = index * 2 + 1;
while (left < this.index) {
int best = (left + 1 < this.index && heap[left + 1] > heap[left]) ? left + 1 : left;
best = heap[best] > heap[index] ? best : index;
if (best == index) {
break;
}
swap(best, index);
index = best;
left = index * 2 + 1;
}
}
// 交换堆中的两个元素
private void swap(int left, int right) {
int temp = heap[left];
heap[left] = heap[right];
heap[right] = temp;
}
}
public int lastStoneWeight(int[] stones) {
MyHeap heap = new MyHeap(stones.length);
for (int stone : stones) {
heap.add(stone);
}
while (heap.size() > 1) {
int x = heap.pop();
int y = heap.pop();
if (x == y) {
continue;
} else {
heap.add(Math.abs(x - y));
}
}
return heap.size() > 0 ? heap.pop() : 0;
}
}