int heap_size; inlineintleft(int idx){ return (idx << 1) + 1; } inlineintright(int idx){ return (idx << 1) + 2; } voidmax_heapify(vector<int>& nums, int idx){ int largest = idx; int l = left(idx), r = right(idx); if (l < heap_size && nums[l] > nums[largest]) largest = l; if (r < heap_size && nums[r] > nums[largest]) largest = r; if (largest != idx) { swap(nums[idx], nums[largest]); max_heapify(nums, largest); } } voidbuild_max_heap(vector<int>& nums){ heap_size = nums.size(); for (int i = (heap_size >> 1) - 1; i >= 0; i--) max_heapify(nums, i); } intfindKthLargest(vector<int>& nums, int k){ build_max_heap(nums); for (int i = 0; i < k; i++) { swap(nums[0], nums[heap_size - 1]); heap_size--; max_heapify(nums, 0); } return nums[heap_size]; }
还有用STL中priority_queue的:
1 2 3 4 5 6
intfindKthLargest(vector<int>& nums, int k){ priority_queue<int> pq(nums.begin(), nums.end()); for (int i = 0; i < k - 1; i++) pq.pop(); return pq.top(); }