# 606.Kth Largest Element II

## 1.Description(Medium)

Find K-th largest element in an array. and N is much larger than k.

### Notice

You can swap elements in the array

**Example**

In array`[9,3,2,4,8]`, the`3rd`largest element is`4`.

In array`[1,2,3,4,5]`, the`1st`largest element is`5`,`2nd`largest element is`4`,`3rd`largest element is`3`and etc.

[**Tags**](https://www.lintcode.com/en/problem/kth-largest-element-ii/#tags)

[Heap](https://www.lintcode.com/tag/heap/)

## 2.Code

用minheap维护。

```
//Version 1:minheap
    public int kthLargestElement2(int[] nums, int k) {
        Queue<Integer> queue=new PriorityQueue<Integer>(k);
        for(int i=0;i<nums.length;i++){
            if(queue.size()<k){
                queue.offer(nums[i]);
            }else{
                if(queue.peek()<nums[i]){
                    queue.poll();
                    queue.offer(nums[i]);
                }
            }
        }
        return queue.peek();
    }

    //version 2:minheap
    public int kthLargestElement22(int[] nums, int k){
         Queue<Integer> queue=new PriorityQueue<Integer>(k);
         for(int element:nums){
             queue.offer(element);
             if(queue.size()>k){
                 queue.poll();
             }
         }
         return queue.peek();
    }
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://junnie.gitbook.io/nine-chapter/8.data-structure/606kth-largest-element-ii.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
