Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Given an unsorted array, find the Kth largest element in it.
- Note: The need is to find the Kth largest element in the sorted order.
- Input format
- First line has the integer N, representing the number of elements in the array
- Second line has N integers representing elements of the array
- Third line has K, which is the Kth largest element to be found
- Output format
- The Kth largest element value needs to be printed
- Constraints
- 1 <= N <= 1e5
- 0 <= Array Values <= 1e9
- 1 ≤ K ≤ N
- Sample Input 1
- 6
- 3 2 1 5 6 4
- 2
- Sample Output 1
- 5
- Explanation 1
- From the given input array, we have to find the second largest value. The first largest is 6 and the second largest is 5, which is the answer.
- Sample Input 2
- 9
- 3 2 3 1 2 4 5 5 6
- 4
- Sample Output 2
- 4
- Explanation 2
- From the given input array, we have to find the fourth largest value. The sorted order with the largest first is 6 5 5 4 3 3 2 2 1. The fourth largest here has the value 4.
- */
- class KthLargestElementInAnArray {
- public:
- int findKthLargest(vector<int>& nums, int k) {
- priority_queue<int>pq;
- int result;
- int n=nums.size();
- for(int i=0;i<n;i++){
- pq.push(nums[i]);
- if(pq.size()>n-(k-1)){
- pq.pop();
- }
- }
- result=pq.top();
- return result;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement