```重构findKthLargest方法使用堆优化
重构'findKthLargest'方法以使用堆优化。新的实现使用一个固定长度的小顶堆来维护当前最小的k个元素。遍历输入数组时,将每个元素与堆顶元素比较,如果大于堆顶元素,则移除堆顶元素并将新元素插入堆中,以确保堆中始终包含数组中最大的k个元素。最后,堆顶元素即为第k大的元素。 此实现的优势在于对于大数据集,它提供了更高效的性能,尤其是在k相对较小而输入数组很大时。通过堆的使用,避免了对整个数组进行完全排序的需要,从而降低了计算复杂度。 ```
This commit is contained in:
parent
2c56c727b1
commit
8b2871b87e
74
src/test/java/cn/whaifree/test/tse.java
Normal file
74
src/test/java/cn/whaifree/test/tse.java
Normal file
@ -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();
|
||||
|
||||
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user