2023每日刷题(十二)
Leetcode—2558.从数量最多的堆取走礼物
大顶堆实现代码
void swap(int *a, int *b) {
int tmp = *a;
*a = *b;
*b = tmp;
}
void downAdjustHeap(int *heap, int low, int high) {
int i = low;
int j = 2 * i + 1;
while(j <= high) {
if(j + 1 <= high && heap[j + 1] > heap[j]) {
j = j + 1;
}
if(heap[j] > heap[i]) {
swap(&heap[j], &heap[i]);
i = j;
j = 2 * i + 1;
} else {
break;
}
}
}
void createHeap(int *arr, int n) {
int i = 0;
for(i = n / 2 - 1; i >= 0; i--) {
downAdjustHeap(arr, i, n - 1);
}
}
long long pickGifts(int* gifts, int giftsSize, int k){
createHeap(gifts, giftsSize);
int i = 0;
for(i = 0; i < k; i++) {
gifts[0] = sqrt(gifts[0]);
downAdjustHeap(gifts, 0, giftsSize - 1);
}
long long ans = 0;
for(i = 0; i < giftsSize; i++) {
ans += gifts[i];
}
return ans;
}
运行结果
之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!