From 8b2871b87e3c2f31233711f64946d54aa16ae311 Mon Sep 17 00:00:00 2001 From: kyriewhluo Date: Mon, 2 Sep 2024 19:57:02 +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相对较小而输入数组很大时。通过堆的使用,避免了对整个数组进行完全排序的需要,从而降低了计算复杂度。 ``` --- src/test/java/cn/whaifree/test/tse.java | 74 +++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 src/test/java/cn/whaifree/test/tse.java diff --git a/src/test/java/cn/whaifree/test/tse.java b/src/test/java/cn/whaifree/test/tse.java new file mode 100644 index 0000000..f9ddbc5 --- /dev/null +++ b/src/test/java/cn/whaifree/test/tse.java @@ -0,0 +1,74 @@ +package cn.whaifree.test; + +public class tse { + + final static Object o = new Object(); + volatile static int num = 0; + public static void main(String[] args) { + + new Thread(new Runnable() { + @Override + public void run() { + try { + for (int i = 0; i < 100; i++) { + synchronized (o) { + while (num % 3 != 0) { + o.wait(); + } + num++; + System.out.println("A"); + o.notifyAll(); + } + + } + } catch (Exception e) { + e.printStackTrace(); + } + } + }).start(); + + new Thread(new Runnable() { + @Override + public void run() { + try { + for (int i = 0; i < 100; i++) { + synchronized (o) { + while (num % 3 != 1) { + o.wait(); + } + num++; + System.out.println("B"); + o.notifyAll(); + } + + } + } catch (Exception e) { + e.printStackTrace(); + } + } + }).start(); + + new Thread(new Runnable() { + @Override + public void run() { + try { + for (int i = 0; i < 100; i++) { + synchronized (o) { + while (num % 3 != 2) { + o.wait(); + } + num++; + System.out.println("C"); + o.notifyAll(); + } + + } + } catch (Exception e) { + e.printStackTrace(); + } + } + }).start(); + + + } +}