• 堆排序


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

  • 相关阅读:
    派生选择器
    HTML 标签
    $.get()
    CC150
    CC150
    CC150
    CC150
    HashMap和HashTable的区别
    CC150
    quickSort
  • 原文地址:https://www.cnblogs.com/fanfuhu/p/15841960.html
Copyright © 2020-2023  润新知