leetcode-215. Kth Largest Element in an Array(スタックソートベース)
原題
Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
For example,
Note: You may assume k is always valid, 1 ≤ k ≤ array’s length.
スタックソート思想に基づく
Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
For example,
Given [3,2,1,5,6,4] and k = 2, return 5.
Note: You may assume k is always valid, 1 ≤ k ≤ array’s length.
スタックソート思想に基づく
public class SolutionHeapFindKthLargest
{
public int FindKthLargest(int[] nums, int k)
{
build_max_heap(nums);
for (int i = 0; i < k; i++)
{
swap(nums, 0, heap_size - 1);
heap_size--;
max_heapify(nums, 0);
}
return nums[heap_size];
}
private int left(int idx)
{
return (idx << 1) + 1;
}
private int right(int idx)
{
return (idx << 1) + 2;
}
private void max_heapify(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, largest);
max_heapify(nums, largest);
}
}
private void build_max_heap(int[] nums)
{
heap_size = nums.Length;
for (int i = (heap_size >> 1) - 1; i >= 0; i--)
max_heapify(nums, i);
}
private void swap(int[] nums, int i, int j)
{
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
private int heap_size;
}