Timeline
Timeline
2025-12-05
init
Quick sort, heap
Problem:
Heap sort
forComplete binary treeNumber the nodes, and the following relationships hold
| Item | 1-based numbering(root=1) | 0-based numbering(root=0) |
|---|---|---|
| Left child | ||
| Right child | ||
| Parent node | ||
| Condition for having at least a left child | ||
| Condition for right child existence | ||
| Leaf node condition | or | |
| Condition for having only a left child | and | |
| Depth (root level=1) | ||
| Depth (root level=0) |
Heap sort:
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950 | using std::vector;class Solution { private: void heapify(vector<int> &vec, int curr, int n) { int left = curr * 2 + 1; int right = curr * 2 + 2; int largest = curr; if (left < n && vec[left] > vec[largest]) { largest = left; } if (right < n && vec[right] > vec[largest]) { largest = right; } if (largest != curr) { std::swap(vec[largest], vec[curr]); //Since the parent and child nodes are swapped, the child's subtree may be affected, so adjust the child's subtree. heapify(vec, largest, n); } } void buildMaxHeap(vector<int> &vec) { int n = vec.size(); // The last node is at position n-1, so its parent is at (n-1-1)/2. for (int i = (n - 2) / 2; i >= 0; i--) { heapify(vec, i, n); } } public: int findKthLargest(vector<int> &nums, int k) { int n = nums.size(); buildMaxHeap(nums); for (int i = 0; i < k - 1; i++) { // pop std::swap(nums[0], nums[n - 1]); n--; heapify(nums, 0, n); } return nums[0]; }}; |
Quicksort
Note that the Hoare implementation doesn’t care where elements equal to the pivot are; it only requires left <= pivot and right >= pivot.
123456789101112131415161718192021222324252627282930313233343536373839 | using std::vector;class Solution { private: int quick_sort(vector<int> &nums, int start, int end, int k) { if (end <= start) { return nums[k]; } int pivot = nums[(start + end) / 2]; int left = start - 1; int right = end + 1; while (left < right) { do { left++; } while (nums[left] < pivot); do { right--; } while (nums[right] > pivot); if (left < right) { std::swap(nums[left], nums[right]); } } // start..=right, right+1..=end if (k<= right) { return quick_sort(nums, start, right, k); } else { return quick_sort(nums, right+1, end, k); } } public: int findKthLargest(vector<int> &nums, int k) { int n = nums.size(); // The K-th largest is the (n-k)-th smallest. return quick_sort(nums, 0, n - 1, n - k); }}; |
