堆排序

 

/**
 * PriorityQueue 原理:最小堆
 * peek获取且不删除堆顶元素,poll获取且删除堆顶元素
 *
* 215. 数组中的第K个最大元素 * https://leetcode-cn.com/problems/kth-largest-element-in-an-array/ */ public class FindKthLargest { public int findKthLargest(int[] nums, int k) { buildMaxHeap(nums); int length = nums.length; for (int i = 0; i < k - 1; i++) { swap(nums, 0, length - 1 - i); heapify(nums, 0, length - 1 - i); } return nums[0]; } public void buildMaxHeap(int[] nums) { int length = nums.length; for (int i = length / 2 - 1; i >= 0; i--) { heapify(nums, i, length); } } public void heapify(int[] nums, int headIndex, int length) { int lagestIndex = headIndex, leftIndex = headIndex * 2 + 1, rightIndex = headIndex * 2 + 2; if (leftIndex < length && nums[leftIndex] > nums[lagestIndex]) { lagestIndex = leftIndex; } if (rightIndex < length && nums[rightIndex] > nums[lagestIndex]) { lagestIndex = rightIndex; } if (lagestIndex != headIndex) { swap(nums, lagestIndex, headIndex); heapify(nums, lagestIndex, length); } } public void swap(int[] nums, int lIndex, int rIndex) { int temp = nums[lIndex]; nums[lIndex] = nums[rIndex]; nums[rIndex] = temp; } }

 

堆排序

 

 

 

堆排序

上一篇:leetcode第518零钱兑换


下一篇:webdriver API