image.png

解决思路

image.png

  1. public class KthLargest {
  2. private PriorityQueue<Integer> queue;
  3. private int limit;
  4. public KthLargest(int k, int[] nums) {
  5. limit = k;
  6. queue = new PriorityQueue<>(k);
  7. for (int num : nums) {
  8. add(num);
  9. }
  10. }
  11. public int add(int val) {
  12. if (queue.size() < limit) {
  13. queue.add(val);
  14. } else if (val > queue.peek()) {
  15. queue.poll();
  16. queue.add(val);
  17. }
  18. return queue.peek();
  19. }
  20. }