From 4895af547b337c03941f83fbab77c97c46ccb653 Mon Sep 17 00:00:00 2001 From: kyriewhluo Date: Fri, 30 Aug 2024 20:06:28 +0800 Subject: [PATCH] =?UTF-8?q?```=E9=87=8D=E6=9E=84findKthLargest=E6=96=B9?= =?UTF-8?q?=E6=B3=95=E4=BD=BF=E7=94=A8=E5=A0=86=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 重构'findKthLargest'方法以使用堆优化。新的实现使用一个固定长度的小顶堆来维护当前最小的k个元素。遍历输入数组时,将每个元素与堆顶元素比较,如果大于堆顶元素,则移除堆顶元素并将新元素插入堆中,以确保堆中始终包含数组中最大的k个元素。最后,堆顶元素即为第k大的元素。 此实现的优势在于对于大数据集,它提供了更高效的性能,尤其是在k相对较小而输入数组很大时。通过堆的使用,避免了对整个数组进行完全排序的需要,从而降低了计算复杂度。 ``` --- .../whaifree/leetCode/Array/LeetCode215.java | 76 +++++++++++++++++++ 1 file changed, 76 insertions(+) diff --git a/src/main/java/cn/whaifree/leetCode/Array/LeetCode215.java b/src/main/java/cn/whaifree/leetCode/Array/LeetCode215.java index dfda3d9..777fe2a 100644 --- a/src/main/java/cn/whaifree/leetCode/Array/LeetCode215.java +++ b/src/main/java/cn/whaifree/leetCode/Array/LeetCode215.java @@ -24,6 +24,82 @@ public class LeetCode215 { // System.out.println(i); } + @Test + public void test1() + { + new sol().findKthLargest(new int[]{3, 2, 1, 5, 6, 4}, 3); + + + } + + class sol{ + /** + * 3 + * / \ + * / \ + * 5 -2147483648 + * / + * 2 右边那个有问题,所以不行 + * @param nums + * @param k + * @return + */ + public int findKthLargest(int[] nums, int k) { + Heap heap = new Heap(k); + for (int num : nums) { + heap.add(num); + } + return 1; + } + } + + + class Heap{ + + + int[] heap = null; + + public Heap(int k) { + this.heap = new int[k + 1]; + Arrays.fill(this.heap, Integer.MIN_VALUE); + } + + public void add(int num) { + heap[heap.length - 1] = num; + shiftUp(heap, heap.length - 1); + } + + + /** + * 固定长度的,让其 shiftUp + * @param nums + * @param numIndex 将 numsIndex 位置上移 + */ + public void shiftUp(int[] nums, int numIndex) { + int k = numIndex; + while (k > 0) { + int parent = (k - 1) / 2; +// if (nums[numIndex] < nums[parent]) { // 小顶堆 + if (nums[k] > nums[parent]) { // 大顶堆 + // 小顶堆,小的上移 + swap(nums, parent, k); + k = parent; + }else { + break; + } + TreeNode.constructTreeByArrayWithInteger(nums); + } + + } + + public void swap(int[] nums, int start, int end) { + int temp = nums[start]; + nums[start] = nums[end]; + nums[end] = temp; + } + + } + class Solution { public int findKthLargest(int[] nums, int k) {