剑指 Offer II 059. 数据流的第 K 大数值 - 力扣(LeetCode) (leetcode-cn.com)
#define MIN 0x80000000
class KthLargest {
int* minHeap;
int K;
public:
KthLargest(int k, vector<int>& nums) {
K = k;
minHeap = new int[k + 1];
int size = nums.size();
int ini_scale = min(size, k);
for (int i = 1; i <= ini_scale; ++i) minHeap[i] = nums[i - 1];
size <= k ? fill(size + 1, k + 1) : add(nums, k, size);
}
int fill(int begin, int end) {
for (int i = begin; i != end; ++i) minHeap[i] = MIN;
return effervesce();
}
int add(vector<int>& nums, int begin, int end) {
effervesce();
for (int i = begin; i != end; ++i) add(nums[i]);
return 0;
}
int add(int val) {
return val < minHeap[1] ? minHeap[1] : sink(val, 1);
}
int effervesce() {
for (int pos = K / 2; pos; --pos) sink(minHeap[pos], pos);
return 0;
}
//核心代码
int sink(int pebble, int pos) {
int bubble;
while ((bubble = pos * 2) <= K) {
bubble != K && minHeap[bubble + 1] < minHeap[bubble] ? ++bubble : 0;
if (pebble <= minHeap[bubble]) break;
minHeap[pos] = minHeap[bubble];
pos = bubble;
}
minHeap[pos] = pebble;
return minHeap[1];
}
};