Advertisement
satishfrontenddev4

Untitled

Jan 6th, 2024
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. Given an unsorted array, find the Kth largest element in it.
  3.  
  4. Note: The need is to find the Kth largest element in the sorted order.
  5.  
  6. Input format
  7. First line has the integer N, representing the number of elements in the array
  8.  
  9. Second line has N integers representing elements of the array
  10.  
  11. Third line has K, which is the Kth largest element to be found
  12.  
  13. Output format
  14. The Kth largest element value needs to be printed
  15.  
  16. Constraints
  17. 1 <= N <= 1e5
  18.  
  19. 0 <= Array Values <= 1e9
  20.  
  21. 1 ≤ K ≤ N
  22.  
  23. Sample Input 1
  24. 6
  25.  
  26. 3 2 1 5 6 4
  27.  
  28. 2
  29.  
  30. Sample Output 1
  31. 5
  32.  
  33. Explanation 1
  34. 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.
  35.  
  36. Sample Input 2
  37. 9
  38.  
  39. 3 2 3 1 2 4 5 5 6
  40.  
  41. 4
  42.  
  43. Sample Output 2
  44. 4
  45.  
  46. Explanation 2
  47. 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.
  48. */
  49.  
  50. class KthLargestElementInAnArray {
  51. public:
  52.     int findKthLargest(vector<int>& nums, int k) {
  53.         priority_queue<int>pq;
  54.         int result;
  55.         int n=nums.size();
  56.         for(int i=0;i<n;i++){
  57.             pq.push(nums[i]);
  58.             if(pq.size()>n-(k-1)){
  59.                 pq.pop();
  60.             }
  61.         }
  62.         result=pq.top();
  63.         return result;
  64.     }
  65. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement