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,

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;
        }

你可能感兴趣的:(算法/LeetCode,模拟排序算法,经典算法,LeetCode题目研究)