update at 2020-10-20 18:15:10 by ehlxr
This commit is contained in:
40
src/main/java/me/ehlxr/leetcode/Solution5.java
Normal file
40
src/main/java/me/ehlxr/leetcode/Solution5.java
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
package me.ehlxr.leetcode;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Comparator;
|
||||||
|
import java.util.PriorityQueue;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author ehlxr
|
||||||
|
* @since 2020-10-20 17:54.
|
||||||
|
*/
|
||||||
|
public class Solution5 {
|
||||||
|
|
||||||
|
public int findKthLargest(int[] nums, int k) {
|
||||||
|
PriorityQueue<Integer> queue = new PriorityQueue<>();
|
||||||
|
for (int val : nums) {
|
||||||
|
queue.add(val);
|
||||||
|
if (queue.size() > k) {
|
||||||
|
queue.poll();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return queue.peek();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
int[] arr = {4, 6, 8, 5, 9};
|
||||||
|
// PriorityQueue<Integer> queue = new PriorityQueue<>();
|
||||||
|
// for (int val : arr) {
|
||||||
|
// queue.add(val);
|
||||||
|
// }
|
||||||
|
// System.out.println(Arrays.toString(queue.toArray()));
|
||||||
|
//
|
||||||
|
//
|
||||||
|
// arr = new int[]{4, 6, 8, 5, 9};
|
||||||
|
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(arr.length, (o1, o2) -> o2 - o1);
|
||||||
|
for (int val : arr) {
|
||||||
|
maxHeap.add(val);
|
||||||
|
}
|
||||||
|
System.out.println(Arrays.toString(maxHeap.toArray()));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
package me.ehlxr.sort;
|
package me.ehlxr.sort;
|
||||||
|
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
|
import java.util.PriorityQueue;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 堆排序
|
* 堆排序
|
||||||
@@ -32,6 +33,20 @@ public class HeapSort {
|
|||||||
int[] arr = {4, 6, 8, 5, 9};
|
int[] arr = {4, 6, 8, 5, 9};
|
||||||
sort(arr);
|
sort(arr);
|
||||||
System.out.println("results: " + Arrays.toString(arr));
|
System.out.println("results: " + Arrays.toString(arr));
|
||||||
|
|
||||||
|
// PriorityQueue<Integer> queue = new PriorityQueue<>();
|
||||||
|
// for (int val : arr) {
|
||||||
|
// queue.add(val);
|
||||||
|
// }
|
||||||
|
// System.out.println(Arrays.toString(queue.toArray()));
|
||||||
|
//
|
||||||
|
//
|
||||||
|
arr = new int[]{4, 6, 8, 5, 9};
|
||||||
|
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(arr.length, (o1, o2) -> o2 - o1);
|
||||||
|
for (int val : arr) {
|
||||||
|
maxHeap.add(val);
|
||||||
|
}
|
||||||
|
System.out.println(Arrays.toString(maxHeap.toArray()));
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void sort(int[] arr) {
|
public static void sort(int[] arr) {
|
||||||
|
|||||||
Reference in New Issue
Block a user